TypeScript泛型

作者:追风剑情 发布于:2018-11-16 14:01 分类:TypeScript

示例一

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"));

运行测试

1111.png

标签: TypeScript

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号