Typescript 必须的所有技巧

B站影视 港台电影 2025-09-16 13:55 1

摘要:interface User { id: number; name: string; age: number;}type PartialUser = Partial;// 等价于 { id?: number; name?: string; age?: numb

1. 基础修饰类

Partial
将类型 T 的所有属性变为可选。

interface User { id: number; name: string; age: number;}type PartialUser = Partial;// 等价于 { id?: number; name?: string; age?: number }

适用场景:如更新用户信息时,允许部分字段可选。

Required
将类型 T 的所有属性变为必填。

interface Config { url?: string; cache?: boolean;}type StrictConfig = Required;// { url: string; cache: boolean }

Readonly
将类型 T 的所有属性设为只读。

interface Point { x: number; y: number;}type ReadonlyPoint = Readonly

;// { readonly x: number; readonly y: number }

适用场景:如 React 组件的 props 应不可变。

2. 结构挑选类

Pick
从 T 中选取指定属性 K。

;// { id: number; name: string }

Omit
从 T 中移除指定属性 K。

Record
构建一个键类型为 K、值类型为 T 的对象。

type Role = 'admin' | 'user';type RoleMap = Record;// { admin: number; user: number }

适用场景:构建枚举到权限的映射结构。

3. 类型过滤类

Exclude
从 T 中排除 U 中的类型。

type T = Exclude;// 'b' | 'c'

适用场景:过滤联合类型中的某些项。

Extract
提取 T 和 U 中共有的类型。

type T = Extract;// 'a'

适用场景:提取允许使用的类型子集。

type T = NonNullable;// string

适用场景:严格模式下确保类型不为空。

4. 函数相关类

ReturnType
提取函数 T 的返回值类型。

Parameters
提取函数 T 的参数类型元组。

ConstructorParameters
提取构造函数 T 的参数类型。

InstanceType
提取构造函数 T 的实例类型。

class Person { name: string; constructor(name: string) { this.name = name; }}type P = InstanceType;// Person

适用场景:基于类类型生成其实例类型。

ThisParameterType
提取函数 T 的 this 类型。

function say(this: { name: string }) { return this.name; }type T = ThisParameterType

OmitThisParameter
移除函数 T 的 this 参数类型。

function say(this: { name: string }) { return this.name; }type Fn = OmitThisParameter;// => string

适用场景:将绑定 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;// 所有属性变为必填

来源:不秃头程序员

相关推荐