TypeScript里面的泛型

泛型

function createArray<T>(length:number, value: T):T[] {
  let result = []
  for(let i = 0; i < length; i++) {
    result.push(value)
  }
  return result
}

createArray<string>(4, 'x')

泛型类

class MyArray<T> {
  private list: T[] = [];
  add(value: T) {
    this.list.push(value)
  }
}

let arr = new MyArray<number>()
arr.add(100)

泛型接口

interface CreateArrayFunc<T> {
  (length: number, value: T): T[]
}

let createArray: CreateArrayFunc<string> = function <T>(length: number, value: T): T[] {
  let result = []
  for (let i = 0; i < length; i++) {
    result.push(value)
  }
  return result
}

createArray(4, 'x')

泛型类型别名

type Cart<T> = {list:T[]} | T[];
let c1:Cart<string> = {list:['1']};
let c2:Cart<number> = [1];

泛型约束

interface Lengthwise {
    length: number;
}

function loggingIdentity<T extends Lengthwise>(arg: T): T {
    console.log(arg.length);
    return arg;
}
相关推荐
©️2020 CSDN 皮肤主题: 技术工厂 设计师:CSDN官方博客 返回首页