摘要:interface User { id: number; name: string; age: number;}type PartialUser = Partial;// 等价于 { id?: number; name?: string; age?: numb
1. 基础修饰类
Partial
将类型 T 的所有属性变为可选。
适用场景:如更新用户信息时,允许部分字段可选。
Required
将类型 T 的所有属性变为必填。
Readonly
将类型 T 的所有属性设为只读。
;// { readonly x: number; readonly y: number }
适用场景:如 React 组件的 props 应不可变。
2. 结构挑选类
Pick
从 T 中选取指定属性 K。
Omit
从 T 中移除指定属性 K。
Record
构建一个键类型为 K、值类型为 T 的对象。
适用场景:构建枚举到权限的映射结构。
3. 类型过滤类
Exclude
从 T 中排除 U 中的类型。
适用场景:过滤联合类型中的某些项。
Extract
提取 T 和 U 中共有的类型。
适用场景:提取允许使用的类型子集。
type T = NonNullable;// string适用场景:严格模式下确保类型不为空。
4. 函数相关类
ReturnType
提取函数 T 的返回值类型。
Parameters
提取函数 T 的参数类型元组。
ConstructorParameters
提取构造函数 T 的参数类型。
InstanceType
提取构造函数 T 的实例类型。
适用场景:基于类类型生成其实例类型。
ThisParameterType
提取函数 T 的 this 类型。
OmitThisParameter
移除函数 T 的 this 参数类型。
适用场景:将绑定 this 的函数转为无 this 的普通函数。
1. 提取 API 返回值并隐藏敏感字段
async function getUser { return { id: 1, name: 'Tom', token: 'secret' };}type User = Omit, 'token'>;// { id: number; name: string }2. 表单局部更新
) {}3. 构建路由映射配置
type Routes = 'home' | 'about' | 'login';type RouteConfig = Record;// { home: string; about: string; login: string }4. 强制 React 组件 Props 必传
interface ButtonProps { label: string; onClick: => void; disabled?: boolean;}type RequiredButton = Required;// 所有属性变为必填来源:不秃头程序员