← 返回首页
叶知秋
2026年3月18日 09:00

TypeScript 高级类型体操

条件类型

type IsString = T extends string ? true : false;
type A = IsString<'hello'>; // true
type B = IsString<42>;       // false

infer 关键字

infer 允许在条件类型中推断类型变量:

type ReturnOf = T extends (...args: any[]) => infer R ? R : never;
type Fn = (x: number) => string;
type R = ReturnOf; // string

模板字面量类型

type EventName = `on${Capitalize}`;
type ClickEvent = EventName<'click'>; // 'onClick'
TypeScript类型系统