初识
泛型,指可以适用于多个类型,并且保证数据不丢失。
用法:使用尖括号包裹类型定义符T(T可以为其他字符)
// 泛型写法,保证数据不丢失,参数类型和返回值类型是一致的。
function identity2<T>(arg: T): T {
return arg;
}
泛型函数
function identity4<T>(arg: Array<T>): Array<T> {
return arg;
}
泛型接口
interface GenericIdentityFn<T> {
(arg: T): T;
}
function identity7<T>(arg: T): T {
return arg;
}
let myIdentity2: GenericIdentityFn<number> = identity7;
泛型类
class GenericNumber<T> {
zeroValue: T;
add: (x: T, y: T) => T;
}
let myGenericNumber = new GenericNumber<number>();
myGenericNumber.zeroValue = 0;
myGenericNumber.add = function (x, y) {
return x + y;
};
配合接口和extends关键字来实现类型约束
interface Lengthwise {
length: number;
}
function loggingIdentity<T extends Lengthwise>(arg: T): T {
console.log(arg.length);
return arg;
}
使用类类型
class BeeKeeper {
hasMask: boolean;
}
class LionKeeper {
nameTag: string;
}
class Animal {}
class Bee extends Animal {
keeper: BeeKeeper;
}
class Lion extends Animal {
keeper: LionKeeper;
}
function createInstance<A extends Animal>(c: new () => A): A {
return new c();
}
createInstance(Lion).keeper.nameTag;
createInstance(Bee).keeper.hasMask;