Partial

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

示例:

  1. interface You {
  2. name: string
  3. }
  4. type Me = Partial<You>
  5. =>
  6. type Me = {
  7. name?: string
  8. }

Required

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

示例:

  1. interface You {
  2. name?: string
  3. }
  4. type Me = Required<You>
  5. =>
  6. type Me = {
  7. name: string
  8. }

Readonly

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

示例:

  1. interface You {
  2. name: string
  3. }
  4. type Me = Readonly<You>
  5. =>
  6. type Me = {
  7. readonly name: string
  8. }

Pick

  1. /**
  2. * From T, pick a set of properties whose keys are in the union K
  3. */
  4. type Pick<T, K extends keyof T> = {
  5. [P in K]: T[P];
  6. };

示例:

  1. interface You {
  2. name: string
  3. age?: number
  4. gender: string
  5. }
  6. type Me = Pick<You, 'age' | 'gender'>
  7. =>
  8. type Me = {
  9. age?: string
  10. gender: string
  11. }

Record

  1. /**
  2. * Construct a type with a set of properties K of type T
  3. */
  4. type Record<K extends keyof any, T> = {
  5. [P in K]: T;
  6. };

示例:

  1. interface You {
  2. name: string
  3. age?: number
  4. }
  5. type Me = Record<You,string>
  6. =>
  7. type Me = {
  8. name: string
  9. age?: string
  10. }

Exclude

  1. /**
  2. * Exclude from T those types that are assignable to U
  3. */
  4. type Exclude<T, U> = T extends U ? never : T;

示例:

  1. type A = number | string | boolean
  2. type B = number | boolean
  3. type Foo = Exclude<A, B>
  4. =>
  5. type Foo = string

Extract

  1. /**
  2. * Extract from T those types that are assignable to U
  3. */
  4. type Extract<T, U> = T extends U ? T : never;

示例:

  1. type A = number | string | boolean
  2. type B = number | boolean
  3. type Foo = Extract<A, B>
  4. =>
  5. type Foo = number | boolean

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. type Foo = {
  2. name: string
  3. age: number
  4. }
  5. type Bar = Omit<Foo, 'age'>
  6. =>
  7. type Bar = {
  8. name: string
  9. }