官方文档地址: https://www.typescriptlang.org/docs/handbook/utility-types.html

Partial

将T中所有属性转为可选属性

  1. interface Todo {
  2. title: string;
  3. description: string;
  4. done: boolean;
  5. }
  6. function updateTodo(todo: Todo, newTodo: Partial<Todo>) {
  7. return { ...todo, ...newTodo };
  8. }
  9. const todo: Todo = {
  10. title: 'First Todo',
  11. description: 'this is the first todo',
  12. done: false
  13. };
  14. updateTodo(todo, { done: true });

Required

将T中所有属性转为必选属性,于Partial相反

Readonly

将T中的属性设置为只读

Record

在TypeScript中类似数组,字符串,接口这些类型都很常见,但是如果要定义一个对象的key和value的值应该怎么办?这个时候就需要用到Record

  1. interface PageInfo {
  2. title: string;
  3. }
  4. type Page = "home" | "about" | "contact";
  5. const nav: Record<Page, PageInfo> = {
  6. about: { title: "about" },
  7. contact: { title: "contact" },
  8. home: { title: "home" },
  9. };
  10. // 比如我需要一个对象,有 ABC 三个属性,属性的值必须是数字,那么就这么写:
  11. type keys = 'A' | 'B' | 'C'
  12. const result: Record<keys, number> = {
  13. A: 1,
  14. B: 2,
  15. C: 3
  16. }

Pick

Pick就是从一个复合类型中取出几个想要的类型的组合

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

Omit

从T中取出除去K的其他所有所有属性,与Pick相对

Exclude

Exclude的作用是将某个类型中属于另一个的类型移除掉

  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

Extract的作用是从T中提取出U 和 Exclude 是相对的