TypeScript 高级技巧我常用的 8 个类型体操大家好我是蔓蔓。TypeScript 写得多了自然会积累一些高级用法。今天整理了几个我日常开发中经常用到的类型体操技巧希望能帮到大家。1. Partial 的深层版本type DeepPartialT { [P in keyof T]?: T[P] extends object ? DeepPartialT[P] : T[P]; }; interface User { name: string; address: { city: string; street: string; }; } type PartialUser DeepPartialUser; // { name?: string; address?: { city?: string; street?: string } }2. 函数参数提取type ParametersT T extends (...args: infer P) any ? P : never; function greet(name: string, age: number): string { return Hello ${name}, you are ${age}; } type GreetParams Parameterstypeof greet; // [string, number]3. 条件类型与 infertype ReturnTypeT T extends (...args: any[]) infer R ? R : any; type GreetReturn ReturnTypetypeof greet; // string4. Omit 和 Pick 的组合使用interface Post { id: number; title: string; content: string; createdAt: Date; } type PostPreview PickPost, title | id; type PostWithoutDate OmitPost, createdAt;5. 模板字面量类型type EventNameT extends string ${T}Changed; type ClickEvent EventNameclick; // clickChanged type FocusEvent EventNamefocus; // focusChanged6. 类型守卫interface Bird { fly(): void; layEggs(): void; } interface Fish { swim(): void; layEggs(): void; } function isFish(pet: Fish | Bird): pet is Fish { return (pet as Fish).swim ! undefined; }7. 索引类型查询interface User { id: number; name: string; email: string; } type UserKeys keyof User; // id | name | email type UserValues User[keyof User]; // number | string8. 映射类型type ReadonlyT { readonly [P in keyof T]: T[P]; }; type WritableT { -readonly [P in keyof T]: T[P]; }; type NullableT { [P in keyof T]: T[P] | null; };类型体操虽然有趣但不要过度使用。团队协作中可读性永远是第一位的。你有什么常用的 TypeScript 技巧吗欢迎分享