Using Class Types in Generics

Using Class Types in Generics

When creating factories in TypeScript using generics, it is necessary to refer to class types by their constructor functions. For example,

function create<T>(c: {new(): T; }): T {
  return new c();
}

A more advanced example uses the prototype property to infer and constrain relationships between the constructor function and the instance side of class types.

class BeeKeeper {
  hasMask: boolean;
}

class ZooKeeper {
  nametag: string;
}

class Animal {
  numLegs: number;
}

class Bee extends Animal {
  keeper: BeeKeeper;
}

class Lion extends Animal {
  keeper: ZooKeeper;
}

function findKeeper<A extends Animal, K> (a: {new(): A;
  prototype: {keeper: K}}): K {

  return a.prototype.keeper;
}

findKeeper(Lion).nametag;  // typechecks!
doc_TypeScript
2016-10-04 19:25:43
Comments
Leave a Comment

Please login to continue.