Last updated on Oct 6, 2022
类型别名中的泛型大多是用来进行工具类型封装。比如:工具类型
type Stringify<T> = {
[K in keyof T]: string
}
type Clone<T> = {
[K in keyof T]: T[K]
}
类似的还有 TypeScript 内置的工具类型,例如:Partial
type Partial<T> = {
[P in keyof T]?: T[P]
}
除此之外,还有一个非常重要的工具:条件类型。
type IsEqual<T> = T extends true ? 1 : 2
type A = IsEqual<true> // 1
type B = IsEqual<false> // 2
type C = IsEqual<'foo'> // 2
在条件类型参与的情况下,泛型通常会被作为条件类型中的判断条件(T extends Condition,或 Type extends T)以及返回值(即 : 两端的值)
像函数可以声明一个参数的默认值一样,泛型同样有着默认值的设定,比如:
type Factory<T = boolean> = T | number | string
const foo: Factory = false
在 TypeScript 中,泛型参数存在默认约束,在 TS 3.9 之前是 any,在 3.9 版本以后则为 unknown。
除了声明默认值以外,泛型还能做泛型约束。
在 JavaScript 中,我们能逻辑中处理:
function add(source: number, add: number) {
if (typeof source !== 'number' || typeof add !== 'number') {
throw new Error('Invalid arguments!')
}
return source + add
}
而在 TypeScript 的泛型中,可以使用 extends 关键字来约束传入的泛型参数必须符合要求。例如:A extends B 意味着 A 是 B 的子类型。
599 extends number 成立;联合类型子集均为联合类型的子类型,1 | 2 是 1 | 2 | 3 | 4 的子类型。{ name: string } 是 {} 的子类型