示例一
class A {}
class B {
//定义属性name
private _name: string = "名字";
public get name() {
return this._name;
}
public set name(value: string) {
this._name = value;
}
}
class GenericNumber<T> { }
//使用泛型定义工厂函数
function createFactory<T>(c: {new(): T; }): T {
return new c();
}
function identity<T>(c: T): T {
return c;
}
interface Keywise {
[key: string]: any;
}
//利用接口定义约束泛型
function getProperty<T extends Keywise, K>(obj: T, key: string): any {
return obj[key];
}
let b = createFactory(B);
console.log(typeof b);
console.log(identity(b));
console.log(getProperty(b, "name"));
运行测试