TypeScript 泛型

2022/02/03 posted in  JS CSS HTML
Tags:  #JavaScript

函数使用泛型

// <> 内可指定多个泛型(用 , 分隔)
function fn<T>(a: T): T {
  return a;
}

// 手动指定泛型类型
let res1 = fn<number>(10);
console.log(res1);

// 自动推断范型类型
let res2 = fn("aa");
console.log(res2);

类使用泛型

class MyClass<T> {
  name: T;
  constructor(name: T) {
    this.name = name;
  }
}

const mc = new MyClass<string>("Tom");

限制泛型

interface Inter {
  length: number;
}

// 限制泛型应该实现特定接口
function fn<T extends Inter>(a: T): T {
  return a;
}

let res1 = fn<string>("aa");
console.log(res1);