TypeScript泛型

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

示例一

  1. class A {}
  2. class B {
  3. //定义属性name
  4. private _name: string = "名字";
  5. public get name() {
  6. return this._name;
  7. }
  8. public set name(value: string) {
  9. this._name = value;
  10. }
  11. }
  12.  
  13. class GenericNumber<T> { }
  14.  
  15. //使用泛型定义工厂函数
  16. function createFactory<T>(c: {new(): T; }): T {
  17. return new c();
  18. }
  19.  
  20. function identity<T>(c: T): T {
  21. return c;
  22. }
  23.  
  24. interface Keywise {
  25. [key: string]: any;
  26. }
  27. //利用接口定义约束泛型
  28. function getProperty<T extends Keywise, K>(obj: T, key: string): any {
  29. return obj[key];
  30. }
  31.  
  32. let b = createFactory(B);
  33. console.log(typeof b);
  34. console.log(identity(b));
  35. console.log(getProperty(b, "name"));

运行测试

1111.png

标签: TypeScript

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号