前言
ts 提供了很多工具类型。
工具类型
Partial 部分类型
interface User {id: number;name: string;}const user: User = {name: "test"} // 会报错,需要用 Partial 工具包起来,表示是 User 类型的一部分const user: Partial<User> = {name: "test"}
Required 必填类型
interface User {id?: number;name: string;}const user: Required<User> = {name: "test"} // 报错,要求必须有 id// Property 'id' is missing in type '{ name: string; }' but required in type 'Required<User>'.
Readonly 只读类型
interface User {id: number;name: string;}const user: Readonly<User> = {id: 123,name: "test"}user.id = 456; // 报错 Cannot assign to 'id' because it is a read-only property
Pick 获取 key 类型(和对象有关)
interface User {id: number;name: string;age: number;}type God = Pick<User, 'id' | 'name'>// 等同于// type God = {// id: number;// name: string;// }
Omit 排除 key 类型(和对象有关)
和 pick 相反的操作
interface User {id: number;name: string;age: number;}type God = Omit<User, 'age'>// 等同于// type God = {// id: number;// name: string;// }
Exclude 排除值类型
type Direction = '东' | '南' | '西' | '北';type Direction2 = Exclude<Direction, '东'>;// 等同于// type Direction2 = "南" | "西" | "北"
Extract 提取值类型
和 exclude 相反
type Direction = '东' | '南' | '西' | '北';type Direction2 = Extract<Direction, '南' | '西' | '北'>// 等同于// type Direction2 = "南" | "西" | "北"
ReturnType 返回值类型
function f(a: number, b: number) {return a + b;}type A = ReturnType<typeof f>;// type A = number
Record 类型
type A = Record<string, number>;// 等同于// type A = {// [x: string]: number;// }
