Exclude<UnionType, ExcludedMembers>
从 UnionType 中剔除既在UnionType又在ExcludedMembers中的类型
type A = 'a' | 'b' | 'c'
type B = 'b'
type C = Exclude<A, B> // 'a' | 'c'
Extract<Type, Union>
它的作用与 Exclude 正好相反,是找出两个类型的交集部分
type A = 'a' | 'b' | 'c'
type B = 'b'
type C = Extract<A, B> // 'b'
Record<Keys, Type>
生成一个对象结构的类型,其中 Keys 为属性且Keys也是有类型限制的,只能接收 string | number | symbol 中的类型, Type 为属性对应的类型,如果 Type 是值类型,则为属性对应的值
type A = 'a' | 'b' | 'c'
type B = 'example' | number
interface O {
age: number
name: string
}
type R1 = Record<A, O> // {a: O; b: O; c: O}
// 试一下反着来
type R2 = Record<O, A> // 会出现下面的报错信息:
// Type 'O' does not satisfy the constraint 'string | number | symbol'.
// Type 'O' is not assignable to type 'symbol'.
// 试一下第二个参数为 B
type R3 = Record<A, B> // {a: B; b: B; c: B}
// 然后继续调换参数的位置
type R4 = Record<B, A> // type C = { [x: number]: A; example: A; }
Readonly<Type>
在这个内置类型工具中,Type 必须是有 property 的类型,如果是传入的 number | string 之类的,且声明的关键字非 const,则仍然可以修改值,常见的 Type 一般是接口、type 定义的结构化的类型(通常是对象字面量形式), 以及数组之类的
const arr: Readonly<number[]> = [1, 2, 3]
arr.push(4) // Error: Property 'push' does not exist on type 'readonly number[]'
interface O {
name: string
}
const obj: Readonly<O> = {
name: 'example'
}
obj.name = 'test' // Error: Cannot assign to 'name' because it is a read-only property.
Required<Type>
Type 一般来说需要一个对象类型或者接口,Required<Type>会将传入的Type中的所有属性都变成必须的
interface Obj {
name: string
desc?: string
}
const o: Required<Obj> = {
name: 'example'
}
// 编辑器会在 o 下面显示一个红色小波浪线,报错信息如下
// Property 'desc' is missing in type '{ name: string; }' but required in
// type 'Required<Obj>'.
// 使用接口定义的时候,desc 属性是可选的,但通过 Required 这个内置的类型工具将
// 其转换为必填的,如果需要一个结构和属性与已定义的接口一致但需要保持所有属性都是
// 必要的,使用 Required 会十分方便
Partial<Type>
与上面的 Required 相反,Partial 的作用则是将所有属性都变为可选的。
本文详细介绍了 TypeScript 中的几个关键类型工具,包括 Exclude 用于从联合类型中排除指定类型,Extract 获取联合类型中的交集,Record 用于创建对象结构类型,Readonly 将类型的所有属性设置为只读,Required 将对象类型的所有属性设为必需,而 Partial 则将所有属性设为可选。这些工具在类型系统的灵活性和精确性方面发挥着重要作用。
4万+

被折叠的 条评论
为什么被折叠?



