Typescript知识点集锦

1、Omit 

TypeScript将Omit<T, K>帮助程序类型添加lib.es5.d.ts类型定义文件中,该文件作为TypeScript编译器的一部分提供。通过该Omit<T, K>类型,我们可以创建一个对象类型,该对象类型从另一个对象类型中省略了特定的属性:

type User = {
  id: string;
  name: string;
  email: string;
};

type UserWithoutEmail = Omit<User, "email">;

// 等价于:
type UserWithoutEmail = {
  id: string;
  name: string;
};

 2、Partial

将每一对中的 key 变为可选,即添加 ?

假设有接口:

interface IUser {
  name: string
  age: number
  department: string
}

经过转化后: type optional = Partial<IUser> 

// optional的结果如下
type optional = {
    name?: string | undefined;
    age?: number | undefined;
    department?: string | undefined;
}

3、keyof

keyof,即 索引类型查询操作符,我们可以将 keyof 作用于泛型 T 上来获取泛型 T 上的所有 public 属性名构成的 联合类型

type unionKey = keyof IUser

// unionKey 结果如下,其获得了接口类型 IUser 中的所有属性名组成的联合类型
type unionKey = "name" | "age" | "department"

T[P]

我们可以通过 keyof 查询索引类型的属性名,那么如何获取属性名对应的属性值类型呢?

这里就用到了 索引访问操作符,与 JavaScript 种访问属性值的操作类似,访问类型的操作符也是通过 [] 来访问的,即 T[P],其中”中括号“中的 P 与 [P in keyof T] 中的 P 相对应。

type unionKey = keyof IUser // "name" | "age" | "department"

type values = IUser[unionKey] // string | number 属性值类型组成的联合类型

 

posted @ 2020-09-18 13:38  小猪冒泡  阅读(309)  评论(0编辑  收藏  举报