Appearance
复习 ts
泛型
<T> 内部的 T 被称为类型变量,有效的字母都能表示类型变量
常见泛型变量代表的意思:
- T (Type) 类型变量
- K (Key) 对象中的键类型
- V (Value) 对象中的值类型
- E (Element) 元素类型
ts
function identity<T, U>(value: T, message: U): T {
console.log(message)
return value
}泛型接口
ts
interface Identities<V, M> {
value: V
message: M
}
// Identities<Number, String>在函数名、接口名、类名 后面 使用 <T, ...> 语法
在什么时候使用泛型?
当函数、接口或类
处理多种数据类型时
在多个地方使用该数据类型时
泛型条件类型
ts
type PromiseType<T> = (args: any[]) => Promise<T>
// 如果 T 是 Promise 那返回 U,否则返回 never 这里 infer U 申明了一个类型变量 U
type UnPromisify<T> = T extends PromiseType<infer U> ? U : never
async function stringPromise() {
return 'Hello, Semlinker!'
}
type extractStringPromise = UnPromisify<typeof stringPromise> // string