series0ne series0ne - 2 months ago 14
TypeScript Question

TypeScript "extends" generic constraint

I am using the

extends
constraint in TypeScript, like so:

class Animal {}
class Lion extends Animal {}
class Bear extends Animal { }

class ZooKeeper<T extends Animal> {
constructor(p: T = new Animal()) {

}
}

new ZooKeeper(new Animal());


But
p: T = new Animal()
contains an error:


Type 'Animal' is not assignable to type 'T'.

constructor Animal(): Animal


Why, and what do I do, in order that I can use
Animal
, in place of
Animal
subtypes?

Source

Answer

Cast your animal to T and it will work.

class ZooKeeper<T extends Animal> {
    constructor(p: T = <T>new Animal()) {

    }
}

According to your own comment (for future readers) you can also do:

class ZooKeeper<T extends Animal> {
    constructor(p: T = new Animal() as T) {

    }
}