[ts]泛型

类型变量,一个组件可以支持多种数据类型的数据

 

基础用法

function identity<T>(arg: T): T {
  return arg;
}
const output = identity('myString');
console.log(output);

 

泛型变量

function identity<T>(arg: T[]): T[] {
  return arg;
}

 

泛型接口

interface GenericIdentityFn<T> {
  (arg: T): T;
}

function identity<T>(arg: T): T {
  return arg;
}

let myIndetity: GenericIdentityFn<number> = identity;

 

泛型类

class GenericNumber<T> {
  zeroValue: T;
  constructor (value: T) {
    this.zeroValue = value;
  }
}

const myGenericNumer = new GenericNumber<number>(123);
console.log(myGenericNumer);

 

泛型约束

interface Lengthwise {
  length: number;
}

function identity<T extends Lengthwise>(arg: T): T {
  console.log(arg.length);
  return arg;
}

 

在泛型中使用类类型

class BeeKeeper {
  hasMask: boolean;
  constructor () {
    this.hasMask = false;
  }
}

class ZooKeeper {
  nametag: string;
  constructor () {
    this.nametag = 'tom';
  }
}

class Animal {
  numLegs: number;
  constructor () {
    this.numLegs = 0;
  }
}

class Bee extends Animal {
  keeper: BeeKeeper;
  constructor () {
    super();
    this.keeper = new BeeKeeper();
  }
}

class Lion extends Animal {
  keeper: ZooKeeper;
  constructor () {
    super();
    this.keeper = new ZooKeeper();
  }
}

function createInstance<A extends Animal>(c: new() => A): A {
  return new c();
}
console.log(createInstance(Lion).keeper.nametag);
console.log(createInstance(Bee).keeper.hasMask);

 

posted @ 2021-11-17 10:04  zhoulixue  阅读(55)  评论(0编辑  收藏  举报