Skip to content

Instantly share code, notes, and snippets.

@roalcantara
Created September 21, 2020 05:10
Show Gist options
  • Save roalcantara/67567147c1058233821d7513a78e3615 to your computer and use it in GitHub Desktop.
Save roalcantara/67567147c1058233821d7513a78e3615 to your computer and use it in GitHub Desktop.
// 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 createInstance<A extends Animal>(c: new () => A): A {
return new c();
}
createInstance(Lion).keeper.nametag;
createInstance(Bee).keeper.hasMask;
// https://www.typescriptlang.org/docs/handbook/generics.html#using-class-types-in-generics
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment