6

减少 TS 重复代码,Omit 用起来真香!

 2 years ago
source link: https://www.fly63.com/article/detial/11563
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

更新日期: 2022-05-23阅读量: 8标签: 代码分享

扫一扫分享

你用过 TypeScript 内置的 Omit 工具类型么?你想知道 Omit 的应用场景和内部是如何实现的么?如果想的话,阅读完本文之后,也许你就懂了。这是一个使用 type 类型别名定义的 User 类型,用于描述用户对象。

type User = {
  id: string; // 用户id
  name: string; // 用户名
  password: string; // 密码
  createdAt: Date; // 创建时间
  updatedAt: Date; // 更新时间
};

其中 id、createdAt 和 updatedAt 这些属性是在创建用户时,由服务端自动生成的。因此在注册用户时,用于描述注册用户对象的 RegisterUser 类型并不需要以上这些属性。那么我们应该如何高效地定义 RegisterUser 类型呢?这时我们可以使用 TS 内置的 Omit 工具类型。

type RegisterUser = Omit<User, "id" | "createdAt" | "updatedAt">;
type RegisterUser = {
    name: string;
    password: string;
}
628af1014b581.jpg

由以上结果可知,id、createdAt 和 updatedAt 这些属性都已经被过滤掉了,所以使用 Omit 工具类型,我们可以很方便地过滤掉对象类型中不需要的属性。

其实 Omit 工具类型还有其它的作用,比如我们可以利用接口继承的方式来实现覆盖已有对象类型中已知属性的类型。具体的实现方式也很简单:

interface UserUI extends Omit<User, "createdAt" | "updatedAt"> {
  createdAt: string;
  updatedAt: string;
}

在以上代码中,UserUI 接口描述的对象用于在页面上显示用户信息,所以我们把原有 User 类型中 createdAt 和 updatedAt 属性的类型都修改成 string 类型。

了解完 Omit 工具类型的应用场景,下面我们来看一下它内部是如何实现的。

// typescript/lib/lib.es5.d.ts
type Omit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>;
628af105adfe7.jpg

由以上代码可知,Omit 工具类型内部使用了 TS 内置的 Pick 和 Exclude 工具类型。

其中 keyof 操作符用于获取某种类型中的所有键,其返回类型是联合类型。而 Exclude 工具类型用于实现类型过滤,即从 keyof T 返回的联合类型中,过滤掉要排除的属性。最终再使用 Pick 工具类型从原有的对象类型中,挑选出需保留的属性,组合成新的对象类型。

来源: 全栈修仙之路

链接: https://www.fly63.com/article/detial/11563


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK