Created
September 21, 2020 05:10
-
-
Save roalcantara/67567147c1058233821d7513a78e3615 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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