// 基础语法:[P in K] 遍历 K 联合类型 type MyReadonly<T> = { readonly [P in keyof T]: T[P] }; type MyPartial<T> = { [P in keyof T]?: T[P] }; type MyRequired<T> = { [P in keyof T]-?: T[P] };
// 通过 as 重映射键(TS 4.1+) type Getters<T> = { [P in keyof T as`get${Capitalize<string & P>}`]: () => T[P]; };
interface Person { name: string; age: number; }
type PersonGetters = Getters<Person>; // { getName: () => string; getAge: () => number }
// 过滤键:通过 never 排除 type ExcludeNullProperties<T> = { [P in keyof T as T[P] extendsnull ? never : P]: T[P]; };
// 应用:将对象中的所有函数类型转换为描述字符串 type FunctionDescriptions<T> = { [P in keyof T as T[P] extendsFunction ? P : never]: string; };
// 应用:事件监听器类型 type EventListeners<T> = { [P in keyof T as`on${Capitalize<string & P>}`]?: (data: T[P]) =>void; };
type ClickEvent = { x: number; y: number }; type Events = { click: ClickEvent }; type Listeners = EventListeners<Events>; // { onClick?: (data: ClickEvent) => void }
// 结合泛型:类型安全的 API 路径 type ApiPath<Resource extendsstring, Action extendsstring> = `/api/${Resource}/${Action}`;
type UserApi = ApiPath<'users', 'list'>; // "/api/users/list"
// 解析模板字面量(通过 infer 提取) type ExtractId<T extendsstring> = T extends`/user/${infer Id}` ? Id : never;
type UserId = ExtractId<'/user/123'>; // "123"
四、类型守卫(Type Guards)
typeof / instanceof
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
functionprocess(value: string | number) { if (typeof value === 'string') { return value.length; // narrowed to string } return value.toFixed(2); // narrowed to number }
classDog{ bark() {} } classCat{ meow() {} }
functionspeak(animal: Dog | Cat) { if (animal instanceof Dog) { animal.bark(); } else { animal.meow(); } }