类型编程
模板字面量类型
字符串模板类型、Uppercase/Lowercase、路由类型推断
模板字面量类型
TS 4.1+ 的类型系统可以操作字符串——拼接、转换大小写、从字符串中提取模式。这是 TS 类型体操的重要工具。
学完本章你将: 掌握字符串模板类型、Uppercase/Lowercase、路由参数推断。
基本字符串操作
typescript
type Greeting = `Hello, ${string}!`; // 匹配模式
let g: Greeting = "Hello, World!"; // ✅
// 内置字符串工具
type Shout = Uppercase<"hello">; // "HELLO"
type Whisper = Lowercase<"HELLO">; // "hello"
type Capital = Capitalize<"hello">; // "Hello"
字符串拼接生成联合类型
typescript
type Event = "click" | "focus" | "blur";
type Handler = `on${Capitalize<Event>}`;
// "onClick" | "onFocus" | "onBlur"
// 笛卡尔积
type Lang = "en" | "zh";
type Key = "title" | "desc";
type I18nKey = `${Lang}.${Key}`;
// "en.title" | "en.desc" | "zh.title" | "zh.desc"
infer 提取路由参数
typescript
// 提取 /users/:id 中的 id
type ExtractRouteParams<T extends string> =
T extends `${string}:${infer Param}/${infer Rest}`
? Param | ExtractRouteParams<`/${Rest}`>
: T extends `${string}:${infer Param}`
? Param
: never;
type Params = ExtractRouteParams<"/users/:id/posts/:postId">;
// "id" | "postId"