官方文档地址: https://www.typescriptlang.org/docs/handbook/utility-types.html
Partial
将T中所有属性转为可选属性
interface Todo {title: string;description: string;done: boolean;}function updateTodo(todo: Todo, newTodo: Partial<Todo>) {return { ...todo, ...newTodo };}const todo: Todo = {title: 'First Todo',description: 'this is the first todo',done: false};updateTodo(todo, { done: true });
Required
Readonly
Record
在TypeScript中类似数组,字符串,接口这些类型都很常见,但是如果要定义一个对象的key和value的值应该怎么办?这个时候就需要用到Record
interface PageInfo {title: string;}type Page = "home" | "about" | "contact";const nav: Record<Page, PageInfo> = {about: { title: "about" },contact: { title: "contact" },home: { title: "home" },};// 比如我需要一个对象,有 ABC 三个属性,属性的值必须是数字,那么就这么写:type keys = 'A' | 'B' | 'C'const result: Record<keys, number> = {A: 1,B: 2,C: 3}
Pick
Pick就是从一个复合类型中取出几个想要的类型的组合
interface Todo {title: string;description: string;done: boolean;}type TodoBase = Pick<Todo, 'title' | 'done'>;const todo: TodoBase = {title: 'First Todo',done: false};
Omit
Exclude
Exclude
type T0 = Exclude<"a" | "b" | "c", "a">; // "b" | "c"type T1 = Exclude<"a" | "b" | "c", "a" | "b">; // "c"type T2 = Exclude<string | number | (() => void), Function>; // string | number
Extract
Extract
