Partial
构造类型T,并将它所有的属性设置为可选的。它的返回类型表示输入类型的所有子类型。
例如:
interface IUser {name: stringage: numberdepartment: string}type optional = Partial<IUser>// optional的结果如下type optional = {name?: string | undefined;age?: number | undefined;department?: string | undefined;}
实现
type Partial<T> = {[P in keyof T]?: T[P];};
在React中的运用
interface FunctionComponent<P = {}> {(props: PropsWithChildren<P>, context?: any): ReactElement<any, any> | null;defaultProps?: Partial<P>; // 设置默认属性}
Record
构造一个类型,其属性名的类型为K,属性值的类型为T。这个工具可用来将某个类型的属性映射到另一个类型上
例如:
interface PageInfo {title: string;}type Page = 'home' | 'about' | 'contact';const x: Record<Page, PageInfo> = {about: { title: 'about' },contact: { title: 'contact' },home: { title: 'home' },};
实现
type Record<K extends keyof any, T> = {[P in K]: T;};
Pick
从类型T中挑选部分属性K来构造类型
interface Todo {title: string;description: string;completed: boolean;}type TodoPreview = Pick<Todo, 'title' | 'completed'>;const todo: TodoPreview = {title: 'Clean room',completed: false,};
在React中的运用
setState<K extends keyof S>(state: ((prevState: Readonly<S>, props: Readonly<P>) => (Pick<S, K> | S | null)) | (Pick<S, K> | S | null),callback?: () => void): void;
Omit
从类型T中获取所有属性,然后从中剔除K属性后构造一个类型
例如:
interface Todo {title: string;description: string;completed: boolean;}type TodoPreview = Omit<Todo, 'description'>;const todo: TodoPreview = {title: 'Clean room',completed: false,};
Exclude
从类型T中剔除所有可以赋值给U的属性,然后构造一个类型。
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
从类型T中提取所有可以赋值给U的类型,然后构造一个类型。
type T0 = Extract<"a" | "b" | "c", "a" | "f">; // "a"type T1 = Extract<string | number | (() => void), Function>; // () => void
ReturnType
由函数类型T的返回值类型构造一个类型。
type T0 = ReturnType<() => string>; // stringtype T1 = ReturnType<(s: string) => void>; // voidtype T2 = ReturnType<(<T>() => T)>; // {}type T3 = ReturnType<(<T extends U, U extends number[]>() => T)>; // number[]type T4 = ReturnType<typeof f1>; // { a: number, b: string }type T5 = ReturnType<any>; // anytype T6 = ReturnType<never>; // anytype T7 = ReturnType<string>; // Errortype T8 = ReturnType<Function>; // Error
