From 9e4e01966009fca5a22ea9bf64c3fbaf46d57c53 Mon Sep 17 00:00:00 2001 From: zekroTJA Date: Fri, 17 Jul 2026 10:52:41 +0200 Subject: [PATCH] add more typescript examples --- 07-type-mapping/main.ts | 4 +++- 08-type-programming/main.ts | 16 +++++++++++++--- 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/07-type-mapping/main.ts b/07-type-mapping/main.ts index f6fc7fc..b7ec098 100644 --- a/07-type-mapping/main.ts +++ b/07-type-mapping/main.ts @@ -4,6 +4,8 @@ enum OpCode { MOVE, } +type PingEvent = Record; + type HelloEvent = { name: string; }; @@ -14,7 +16,7 @@ type MoveEvent = { }; type OpArgsMapping = { - [OpCode.PING]: {}; + [OpCode.PING]: PingEvent; [OpCode.HELLO]: HelloEvent; [OpCode.MOVE]: MoveEvent; }; diff --git a/08-type-programming/main.ts b/08-type-programming/main.ts index a057bdf..97d718f 100644 --- a/08-type-programming/main.ts +++ b/08-type-programming/main.ts @@ -1,13 +1,23 @@ -type ParseUrlParams = Url extends `${infer Start}/${infer Rest}` - ? ParseUrlParams & ParseUrlParams +type ParseUrlParamsRaw = Url extends `${infer Start}/${infer Rest}` + ? ParseUrlParamsRaw & ParseUrlParamsRaw : Url extends `{${infer Param}}` ? { [P in Param]: string } : {}; +// ParseUrlParamsRaw allows passing objects with any keys (i.e. `{name: "foo"}`) even though +// an empty object is expected (`{}`). This type constraint enforces this by checking if +// the result of ParseUrlParamsRaw is `{}`. `keyof {}` evaluates to `never`, so +// when `{}` is evaluated an empty Record is expected, otherwise the result of +// ParseUrlParamsRaw is expected. +type ParseUrlParams = keyof ParseUrlParamsRaw extends never + ? Record + : ParseUrlParamsRaw; + function navigate

(path: P, params: ParseUrlParams

) { // ... } function main() { - navigate("/foo/bar", { foo: "asd" }); + navigate("/hello", {}); + navigate("/hello/{name}", { name: "foo" }); }