泛型
function identity<T> (arg: T): T {
return arg;
}
console.log(identity<string>('string'));
console.log(identity('string'));
function loggingIdentityA<T> (args: Array<T>): Array<T> {
return args;
}
复制代码
泛型类型
泛型函数
function identityA<T> (arg: T) {
return arg;
}
let identityB: <T>(arg: T) => T = identityA;
let identityC: {<T>(arg: T): T} = identity;
复制代码
泛型接口
interface GenericIdentity {
<T>(arg: T): T;
}
function identityD<T> (arg: T): T {
return arg;
}
let identityE: GenericIdentity = identityD;
console.log(identityE<string>('string'));
复制代码
泛型类
class GenericNumber<T> {
zeroVale: T;
add: (x: T, y: T) => T;
}
let genericNumber = new GenericNumber<number>();
genericNumber.zeroVale = 0;
genericNumber.add = function(x, y) { return x + y; };
复制代码
泛型约束
interface Lengthwise { // 此处进行约束
length: number;
}
function loggingIdentityB<T extends Lengthwise>(arg: T): T {
console.log(arg.length);
return arg;
}
loggingIdentityB(12); // Argument of type '12' is not assignable to parameter of type 'Lengthwise'.
loggingIdentityB([1,2]);
复制代码
在泛型约束中使用类型参数
// 声明一个类型参数,且它被另一个类型参数所约束
function getProperty(obj: T, key: K) { // 此例fail
return obj[key];
}
let x = { a: 1, b: 2, c: 3, d: 4 };
getProperty(x, "a");
getProperty(x, "m");
复制代码
在泛型里使用类类型
// 使用原型属性推断并约束构造函数与类实例的关系
function create<T>(c: new() => T): T { // 实例
return new c();
}
class BeeKeeper {
hasMask: boolean;
}
class ZooKeeper {
nameTag: string;
}
class Animal {
numLegs: number;
}
class Bee extends Animal {
keeper: BeeKeeper;
}
class Lion extends Animal {
keeper: ZooKeeper;
}
function createInstance<A extends Animal>(c: new() => A): A {
return new c();
}
createInstance(Lion).keeper.nameTag = 'nameTag';
createInstance(Bee).keeper.hasMask = true;
复制代码