Partial

构造类型T,并将它所有的属性设置为可选的。它的返回类型表示输入类型的所有子类型。

例如:

  1. interface IUser {
  2. name: string
  3. age: number
  4. department: string
  5. }
  6. type optional = Partial<IUser>
  7. // optional的结果如下
  8. type optional = {
  9. name?: string | undefined;
  10. age?: number | undefined;
  11. department?: string | undefined;
  12. }

实现

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

在React中的运用

  1. interface FunctionComponent<P = {}> {
  2. (props: PropsWithChildren<P>, context?: any): ReactElement<any, any> | null;
  3. defaultProps?: Partial<P>; // 设置默认属性
  4. }

Record

构造一个类型,其属性名的类型为K,属性值的类型为T。这个工具可用来将某个类型的属性映射到另一个类型上
例如:

  1. interface PageInfo {
  2. title: string;
  3. }
  4. type Page = 'home' | 'about' | 'contact';
  5. const x: Record<Page, PageInfo> = {
  6. about: { title: 'about' },
  7. contact: { title: 'contact' },
  8. home: { title: 'home' },
  9. };

实现

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

Pick

从类型T中挑选部分属性K来构造类型

  1. interface Todo {
  2. title: string;
  3. description: string;
  4. completed: boolean;
  5. }
  6. type TodoPreview = Pick<Todo, 'title' | 'completed'>;
  7. const todo: TodoPreview = {
  8. title: 'Clean room',
  9. completed: false,
  10. };

在React中的运用

  1. setState<K extends keyof S>(
  2. state: ((prevState: Readonly<S>, props: Readonly<P>) => (Pick<S, K> | S | null)) | (Pick<S, K> | S | null),
  3. callback?: () => void
  4. ): void;

Omit

从类型T中获取所有属性,然后从中剔除K属性后构造一个类型

例如:

  1. interface Todo {
  2. title: string;
  3. description: string;
  4. completed: boolean;
  5. }
  6. type TodoPreview = Omit<Todo, 'description'>;
  7. const todo: TodoPreview = {
  8. title: 'Clean room',
  9. completed: false,
  10. };

Exclude

从类型T中剔除所有可以赋值给U的属性,然后构造一个类型。

  1. type T0 = Exclude<"a" | "b" | "c", "a">; // "b" | "c"
  2. type T1 = Exclude<"a" | "b" | "c", "a" | "b">; // "c"
  3. type T2 = Exclude<string | number | (() => void), Function>; // string | number

Extract

从类型T中提取所有可以赋值给U的类型,然后构造一个类型。

  1. type T0 = Extract<"a" | "b" | "c", "a" | "f">; // "a"
  2. type T1 = Extract<string | number | (() => void), Function>; // () => void

ReturnType

由函数类型T的返回值类型构造一个类型。

  1. type T0 = ReturnType<() => string>; // string
  2. type T1 = ReturnType<(s: string) => void>; // void
  3. type T2 = ReturnType<(<T>() => T)>; // {}
  4. type T3 = ReturnType<(<T extends U, U extends number[]>() => T)>; // number[]
  5. type T4 = ReturnType<typeof f1>; // { a: number, b: string }
  6. type T5 = ReturnType<any>; // any
  7. type T6 = ReturnType<never>; // any
  8. type T7 = ReturnType<string>; // Error
  9. type T8 = ReturnType<Function>; // Error