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,
1 2 3 | 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | 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! |
Please login to continue.