TypeScript学习:泛型
定义
具有以下特点的数据类型叫泛型:
- 定义时不明确使用时必须明确成某种具体数据类型的数据类型【泛型的宽泛】
- 编译期间进行数据类型检查的数据类型【泛型的严谨】
class 类名<泛型形参类型> 泛型形参类型一般有两种表示:
- A-Z任何一个字母(绝大多数情况用此)
- 语义化的单词来表示
ts
class ArrayList<T> {
array: Array<T>
add(data: T) {}
}
interface Ref1 {
value: any
}
let ref1: Ref1 = {
value: {
name: 'fri',
age: 24
}
}
// 用`any`,如果是 obj,后续拿不到任何类型和方法。这时就需要用到泛型了
interface Ref<V> {
value: V
}
let ref: Ref<string> = {
value: 'abc'
}
type Student = {name: string, age: number}
let stu: Ref<Student> = {
value: {name: 'fys', age: 30}
}泛型约束
复习:keyof表示获取一个类 或 一个对象类型 或 一个接口类型 的所有属性名[key]组成的联合类型
ts
class Order {
orderid!: number
ordername!: string
static count: number
printOrd() {}
static getCount() {}
}
// 索引类型访问
type OrdIdType = Order['orderid']
// 获取类中实例的属性和方法 组成的联合类型
type OrdInstAttrNames = keyof Order
// 改造上述,泛型约束
type InstancePropKeys<T extends object> = keyof T
type OrdInstAttrNames2 = InstancePropKeys<Order>vue3源码中的泛型约束
ts
class ObjectRefImpl<T extends object, K extends keyof T> {
public readonly __v_isRef = true
constructor(private readonly _object: T, private readonly _key: K) {}
get value() {
return this._object[this._key]
}
set value(newVal) {
this._object[this._key] = newVal
}
}