How can I declare a class
type, so that I ensure the object is a constructor of a general class?
In the following example, I want to know which type should I give to AnimalClass
so that it could either be Penguin
or Lion
:
class Animal {
constructor() {
console.log("Animal");
}
}
class Penguin extends Animal {
constructor() {
super();
console.log("Penguin");
}
}
class Lion extends Animal {
constructor() {
super();
console.log("Lion");
}
}
class Zoo {
AnimalClass: class // AnimalClass could be 'Lion' or 'Penguin'
constructor(AnimalClass: class) {
this.AnimalClass = AnimalClass
let Hector = new AnimalClass();
}
}
Of course, the class
type does not work, and it would be too general anyway.
Like that:
Or just:
typeof Class
is the type of the class constructor. It's preferable to the custom constructor type declaration because it processes static class members properly.Solution from typescript interfaces reference:
So the previous example becomes: