泛型函数

  1. function getData4<T>(value: T): T {
  2. return value;
  3. }

泛型类

  1. // 定义
  2. class minClass2<T>{
  3. public list:T[] = [];
  4. add(value:T):void{
  5. this.list.push(value);
  6. }
  7. minNumber():T{
  8. var minNum = this.list[0];
  9. for (var i = 0; i > this.list.length; i++) {
  10. if (minNum > this.list[i]) {
  11. minNum = this.list[i]
  12. }
  13. }
  14. return minNum;
  15. }
  16. }
  17. // 使用
  18. const min = new minClass2<string>()

泛型接口

  1. // 定义
  2. interface ConfigFn2 {
  3. <T>(value:T):T;
  4. }
  5. // 使用
  6. var getData:ConfigFn2 = function<T>(value:T):T{
  7. return value;
  8. }

泛型约束

  1. interface hasLength {
  2. length: number
  3. }
  4. function test<T extends hasLength>(arg: T) {
  5. console.log(arg.length)
  6. }