TS 工具类型有很多,如下:Partial、Required、Readonly、Pick/Omit、Exclude/Extract、ReturnType、Record、Map,下面分别举例说明一下。
一、Partial
这是一种处理对象类型的工具。Partial 指的就是返回指定类型的部分类型,如下例中的 user 就可以不设置 name 字段,因为它的类型只是部分的 User 类型。
interface User {
id: number;
name: string;
}
const user: Partial<User> = {
id: 1
}
二、Required
这是一种处理对象类型的工具。Required 的作用与 Partial 有相反的感觉,下例中虽然 User 中的 id 是可选的,但是加了 Required 之后每个字段都会变成必选的,如果 user 没有 id 字段的话将会出现报错。
interface User {
id?: number;
name: string;
}
const user: Required<User> = {
id: 1, // 没有 id 字段会报错
name:"Tom"
}
三、Readonly
这是一种处理对象类型的工具。Readonly 的作用相当于给类型中的每个字段加上 readonly 限制,下例中给 user 加上 Readonly 后再给 id 赋值会出现报错的情况。
interface User {
id: number;
name: string;
}
const user: Readonly<User> = {
id: 1,
name:"Tom"
}
user.id = 23 // 报错,提示不能给 id 赋值
四、Pick 和 Omit
这是一种处理对象类型的工具。Pick 的作用选择特定类型中的部分字段,Omit 的作用是设置不需要选择的字段,如下当设置了 Pick<User, 'id'>
后 user 的类型就只能包括 id 了,如果设置 name 的话会报错,设置了 Omit<User, 'id'>
后 user 的类型就除去了 id,只包括 name 字段。
interface User {
id: number;
name: string;
}
const user: Pick<User, 'id'> = {
id: 1
}
interface User {
id: number;
name: string;
}
const user: Omit<User, 'id'> = {
name: "Tom"
}
五、Extract 和 Exclude
这是一种处理联合类型的工具。这一组和上一组的作用类似,都是选择和除去特定类型的,使用场景如下:
type A = '东' | '西' | '南' | '北'
type B = Extract<A, '东' | '西'> // B 的类型为 '东' | '西'
type A = '东' | '西' | '南' | '北'
type B = Exclude<A, '东' | '西'> // B 的类型为 '南' | '北'
六、Record
这是一种处理联合类型的工具。Record 可以用于给对象定义 key 和 value 的类型,要注意的是 Record 定义 key 的类型时只限定 number、string、symbol 三种类型,使用场景如下:
type User = Record<string, number | string>
// 相当于 type User = {[x: string]: string | number;}
七、ReturnType
这是一个可以返回函数返回类型的工具类型,只能用于函数,如果用于其他地方会导致报错,使用场景如下,下例中就可以返回 fn 函数返回值的类型。
// 场景一:用于实际函数
function fn(a: number, b: number) {
return 'a + b'
}
type ReturnFnType = ReturnType<typeof fn> //ReturnFnType 的类型为 string
// 场景二:用于函数类型
type TestFunction = (a: number, b: number) => number
type TestReturn = ReturnType<TestFunction>
const a: TestReturn = 10 // 可正常赋值,因为 TestReturn 类型为 number
本篇文章只是简单总结一下一些常见场景的用法,欢迎留言讨论。