keyof

Object.keys 用于提取对象类型的键,keyof 则用于提取 interface 的键。

  1. interface Point {
  2. x: number;
  3. y: number;
  4. }
  5. // type keys = "x" | "y"
  6. type keys = keyof Point;

in

in 用来遍历枚举类型。

  1. type keys = "x" | "y"
  2. type Obj = {
  3. [p in keys]: string;
  4. } // -> { x: string, y: string }

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

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

Partial 源码中,keyof 拿到 T 的所有属性值,然后通过 in 遍历这些属性值,赋值给 P,最后通过 T[P] 取得相应的属性值。

Required

将类型中所有选项都变成必选,去除所有的非必须。

  1. /**
  2. * Make all properties in T required
  3. */
  4. type Required<T> = {
  5. [P in keyof T]-?: T[P];
  6. };

例如:

  1. export interface Contact{
  2. name: string;
  3. phone?: string;
  4. email?: string;
  5. avatar?: string;
  6. userid?: string;
  7. }
  8. export interface RequiredContact= Required<Contact>
  9. RequiredContact {
  10. name: string;
  11. phone: string;
  12. email: string;
  13. avatar: string;
  14. userid: string;
  15. }

Partial

将类型中所有选项都变成可选。

  1. /**
  2. * Make all properties in T optional
  3. */
  4. type Partial<T> = {
  5. [P in keyof T]?: T[P];
  6. };

例如:

  1. export interface Contact{
  2. name?: string;
  3. phone: string;
  4. email?: string;
  5. avatar: string;
  6. userid?: string;
  7. }
  8. export interface RequiredContact= Partial<Contact>
  9. RequiredContact {
  10. name?: string;
  11. phone?: string;
  12. email?: string;
  13. avatar?: string;
  14. userid?: string;
  15. }

Pick

选取类型中指定类型。

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

例如:

  1. export interface Contact{
  2. name?: string;
  3. phone: string;
  4. email?: string;
  5. avatar: string;
  6. userid?: string;
  7. }
  8. export interface ContactPick extends Pick<Contact, 'name' | 'phone'> {};
  9. ContactPick {
  10. name?: string;
  11. phone: string;
  12. }

Omit

去除类型中的某些类型

  1. /**
  2. * Construct a type with the properties of T except for those in type K.
  3. */
  4. type Omit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>;

例如:

  1. export interface Contact{
  2. name?: string;
  3. phone: string;
  4. email?: string;
  5. avatar: string;
  6. userid?: string;
  7. }
  8. export type OmitEmailContact = Omit<Contact, 'email' >;
  9. OmitEmailContact {
  10. name?: string;
  11. phone: string;
  12. avatar: string;
  13. userid?: string;
  14. }

参考