Take a look at this example: https://www.typescriptlang.org/docs/handbook/2/generics.html#using-class-types-in-generics
To make it work, I just need to call a static method before instantiation. Let's adjust the example like this:
class BeeKeeper {
hasMask: boolean = true;
}
class ZooKeeper {
nametag: string = "Mikle";
}
class Animal {
static beforeInit() {
console.log('do something here');
};
numLegs: number = 4;
}
class Bee extends Animal {
static beforeInstantiate() {
console.log('do some bee stuff here');
};
keeper: BeeKeeper = new BeeKeeper();
}
class Lion extends Animal {
static beforeInstantiate() {
console.log('do some lion stuff here');
};
keeper: ZooKeeper = new ZooKeeper();
}
function createInstance<A extends Animal>(c: new () => A): A {
c.beforeInstantiate(); // TS2339: Property 'beforeInit' does not exist on type 'new () => A'.
return new c();
}
createInstance(Lion).keeper.nametag;
createInstance(Bee).keeper.hasMask;
I added a static
method to the Animal
class and called it in the createInstance
function just before instantiation. However, an error occurred:
TS2339: Property 'beforeInit' does not exist on type 'new () => A'.
How can I modify the type of c
to let TypeScript recognize the static functions?