共计 2040 个字符,预计需要花费 6 分钟才能阅读完成。
在映射类型里,新类型以雷同的模式去转换旧类型的每个属性。
Partial
将每个属性转换为可选属性
type Partial<T> = {[P in keyof T]?: T[P];
}
例子:
type PersonPartial = Partial<Person>;
// ^ = type PersonPartial = {
// name?: string | undefined;
// age?: number | undefined;
// }
Readonly
将每个属性转换为只读属性
type Readonly<T> = {readonly [P in keyof T]: T[P];
}
例子:
type ReadonlyPerson = Readonly<Person>;
// ^ = type ReadonlyPerson = {
// readonly name: string;
// readonly age: number;
// }
Nullable
转换为旧类型和 null 的联结类型
type Nullable<T> = {[P in keyof T]: T[P] | null
}
例子:
type NullablePerson = Nullable<Person>;
// ^ = type NullablePerson = {
// name: string | null;
// age: number | null;
// }
Pick
选取一组属性指定新类型
type Pick<T, K extends keyof T> = {[P in K]: T[P];
}
例子:
interface Todo {
title: string;
description: string;
completed: boolean;
}
type TodoPreview = Pick<Todo, "title" | "completed">;
const todo: TodoPreview = {
title: "Clean room",
completed: false,
};
todo;
// ^ = const todo: TodoPreview
Record
创立一组属性指定新类型,罕用来申明一般 Object 对象
type Record<K extends keyof any, T> = {[P in K]: T;
}
Record 属于非同态,实质上会创立新属性,不会拷贝属性修饰符。
例子:
interface PageInfo {title: string;}
type Page = "home" | "about" | "contact";
const nav: Record<Page, PageInfo> = {about: { title: "about"},
contact: {title: "contact"},
home: {title: "home"},
};
nav.about;
// ^ = const nav: Record
Exclude
去除交加,返回残余的局部
type Exclude<T, U> = T extends U ? never : T
例子:
interface Props {
a?: number;
b?: string;
}
const obj: Props = {a: 5};
const obj2: Required<Props> = {a: 5};
Property 'b' is missing in type '{a: number;}' but required in type 'Required<Props>'.
Omit
实用于键值对对象的 Exclude,去除类型中蕴含的键值对
type Omit = Pick<T, Exclude<keyof T, K>>
例子:
interface Todo {
title: string;
description: string;
completed: boolean;
}
type TodoPreview = Omit<Todo, "description">;
const todo: TodoPreview = {
title: "Clean room",
completed: false,
};
ReturnType
获取返回值类型,个别为函数
type ReturnType<T extends (...args: any) => any>
= T extends (...args: any) => infer R ? R : any;
例子:
declare function f1(): { a: number; b: string};
type T4 = ReturnType<typeof f1>;
// ^ = type T4 = {
// a: number;
// b: string;
// }
Required
将每个属性转换为必选属性
type Required<T> = {[P in keyof T]-?: T[P]
}
例子:
interface Props {
a?: number;
b?: string;
}
const obj: Props = {a: 5};
const obj2: Required<Props> = {a: 5};
// Property 'b' is missing in type '{a: number;}' but required in type 'Required<Props>'.
除此以外,还有很多相似的映射类型,能够参考 TypeScript: Documentation 取得更具体的信息。
正文完