thedayturns
thedayturns

Reputation: 10823

Can I specify the type of a class that extends from another class?

In Typescript it is possible to say "the type of this variable is a specific class rather than an instance:"

const x: typeof Animal = Animal

It's also possible with generics to say that a type inherits another type:

function myFunction<T extends Animal>(someAnimal: T) { /* ... */ }

Can I do both and say that "the type of this variable is a specific class or a class that inherits from that class"?

If y had such a type, then I could do y = Animal or y = Tiger.

Upvotes: 1

Views: 167

Answers (1)

basarat
basarat

Reputation: 275857

"the type of this variable is a specific class or a class that inherits from that class

When you have x: typeof Animal it already accepts Animal or anything that extends Animal. This is because TypeScript is structurally typed.

Sample:

class Animal{
    animal: number;
};
class Tiger extends Animal{
    tiger: number;
};


let x: typeof Animal;
x = Animal;
x = Tiger;

And there are lots of reasons why this is a good idea : https://basarat.gitbooks.io/typescript/content/docs/why-typescript.html

Update

Based on the comment

Wait a sec. So this definitely works, but doing something like myFunction(x: typeof Animal) and then myFunction(Tiger) doesn't work - it gives an error about incompatible types. Why not??

It works as well.

class Animal{
    animal: number;
};
class Tiger extends Animal{
    tiger: number;
};

function iTakeAnimalClasses(x: typeof Animal){}
iTakeAnimalClasses(Animal);
iTakeAnimalClasses(Tiger);

Upvotes: 2

Related Questions