Pick
interface Todo {
title: string;
description: string;
completed: boolean;
}
type TodoPreview = Pick<Todo, 'title' | 'completed'>;
const todo: TodoPreview = {
title: 'Clean room',
completed: false,
};
Omit
interface Todo {
title: string;
description: string;
completed: boolean;
}
type TodoPreview = Omit<Todo, 'description'>;
const todo: TodoPreview = {
title: 'Clean room',
completed: false,
};
Partial
interface Todo {
title: string;
description: string;
}
function updateTodo(todo: Todo, fieldsToUpdate: Partial<Todo>) {
return { ...todo, ...fieldsToUpdate };
}
const todo1 = {
title: 'organize desk',
description: 'clear clutter',
};
const todo2 = updateTodo(todo1, {
description: 'throw out trash',
});
Required
interface Props {
a?: number;
b?: string;
};
const obj: Props = { a: 5 }; // OK
const obj2: Required<Props> = { a: 5 }; // Error: property 'b' missing
Extract
type T0 = Extract<"a" | "b" | "c", "a" | "f">; // "a"
type T1 = Extract<string | number | (() => void), Function>; // () => void
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
+
-
这两个关键字用于映射类型中给属性添加修饰符,比如-?
就代表将可选属性变为必选,-readonly
代表将只读属性变为非只读.
type Required<T> = { [P in keyof T]-?: T[P] };
/**
* Make all properties in T optional
*/
// 将 T 类型中的所有属性变成可选的
type Partial<T> = {
[P in keyof T]?: T[P];
};
/**
* Make all properties in T required
*/
// 将 T 类型中的所有属性变成必选的
type Required<T> = {
[P in keyof T]-?: T[P];
};
/**
* Make all properties in T readonly
*/
// 将 T 中所有属性变成只读的
type Readonly<T> = {
readonly [P in keyof T]: T[P];
};
/**
* From T, pick a set of properties whose keys are in the union K
*/
// 将 T 类型中的 K 属性挑出来
type Pick<T, K extends keyof T> = {
[P in K]: T[P];
};
/**
* Construct a type with a set of properties K of type T
*/
type Record<K extends keyof any, T> = {
[P in K]: T;
};
/**
* Exclude from T those types that are assignable to U
*/
// 从类型 T 中去除所有可以赋值给 U 的属性,然后构造一个类型
type Exclude<T, U> = T extends U ? never : T;
/**
* Extract from T those types that are assignable to U
*/
// 取 T 类型 和 U 类型 属性的交集
type Extract<T, U> = T extends U ? T : never;
/**
* Construct a type with the properties of T except for those in type K.
*/
// 从 T 类型 中排除 K 属性
type Omit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>;
示例:
interface T {
a: string;
b: number;
}
interface U {
a: string;
}
type A = Exclude<keyof T, keyof U>;
const a: A = 'b'
type B = Extract<keyof T, keyof U>;
const b: B = 'a'
type C = Omit<T, keyof U>;
const c: C = {
b: 1
}