TS高级技巧(Pick,Partial等)

本文介绍了TypeScript中keyof和in操作符的用法,如何利用它们增强get函数的类型安全性,以及如何结合Exclude和Omit创建更复杂的类型工具。此外,还探讨了Required、Partial和Pick类型工具在接口定制中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.1 keyof

keyofObject.keys 略有相似,只不过 keyofinterface 的键

interface Point {
  x: number;
  y: number;
}

// type keys = "x" | "y"
type keys = keyof Point;

假设有一个 object 如下所示,我们需要使用 typescript 实现一个 get 函数来获取它的属性值

const data = {
  a: 3,
  hello: 'world'
}

function get(o: object, name: string) {
  return o[name]
}

我们刚开始可能会这么写,不过它有很多缺点

  1. 无法确认返回类型:这将损失ts 最大的类型校验功能
  2. 无法对 key做约束:可能会犯拼写错误的问题

这时可以使用 keyof 来加强 get 函数的类型功能

function get<T extends object, K extends keyof T>(o: T, name: K): T[K] {
  return o[name]
}

1.2 in

in 则可以遍历枚举类型,例如

type Keys = "a" | "b"
type Obj =  {
  [p in Keys]: any
} // -> { a: any, b: any }

keyof 产生枚举类型,,in 使用枚举类型遍历,所以他们经常一起使用,看下 Partial 源码

type Partial<T> = { [P in keyof T]?: T[P] };

上面语句的意思是 keyof T 拿到 T 所有属性名,然后 in 进行遍历,将值赋给 P,最后 T[P] 取得相应属性的值

2. Required & Partial & Pick

type Required<T> = {
  [P in keyof T]-?: T[P];
};

type Partial<T> = {
  [P in keyof T]?: T[P];
};

type Pick<T, K extends keyof T> = {
  [P in K]: T[P];
};

interface User {
  id: number;
  age: number;
  name: string;
};

// 相当于: type PartialUser = { id?: number; age?: number; name?: string; }
type PartialUser = Partial<User>

// 相当于: type PickUser = { id: number; age: number; }
type PickUser = Pick<User, "id" | "age">

4. never & Exclude & Omit

type Exclude<T, U> = T extends U ? never : T;

// 相当于: type A = 'a'
type A = Exclude<'x' | 'a', 'x' | 'y' | 'z'>

结合 Exclude 可以推出 Omit 的写法

type Omit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>;

interface User {
  id: number;
  age: number;
  name: string;
};

// 相当于: type PickUser = { age: number; name: string; }
type OmitUser = Omit<User, "id">
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值