定义

静态编写的时候并不确定传入的参数是什么类型。

泛型变量

  • 已知外层数据类型
  • 未知内部数据类型
  • 例如:Arrary

    泛型接口

    1. interface reurnFn<T>{
    2. (para:T):T
    3. }
    4. // 因为returnFn是个类型函数接口
    5. const returnFn:reurnFn<number> = para=>para

泛型类

  1. class<T>{
  2. num:T
  3. fn(item:T){
  4. return item
  5. }
  6. }

泛型约束

约束

泛型约束于索引类型

  1. // keyof T T的所有key
  2. function getValue<T extends object,U extends keyof T>(obj:T,key:U){
  3. return obj[key]
  4. }

多重类型进行泛型约束

  • 建立一个超接口,约束超接口
  • 交叉类型约束(&) ```typescript interface superInterface extends interface1,interface2{}

class demo{ // you can use the attribute of interface1 and interface2
}

class demo{ // you can use the attribute of interface1 and interface2
}

  1. <a name="SfuLB"></a>
  2. ### 泛型与new
  3. ```typescript
  4. // 参数 type 的类型 {new(): T} 就表示此泛型 T 是可被构造的
  5. function factory<T>(type: {new(): T}): T {
  6. return new type() // ok
  7. }