Linus Norton
Linus Norton

Reputation: 557

Array of generic classes

I have an animal Hospital that has an array of Vets, each Vet specialises in a particular Animal.

interface Animal {}

class Dog implements Animal {}
class Cat implements Animal {}

class Vet<T extends Animal> {
  waitingList: T[];
}

class Hospital {
  vets: Vet[]
}

I am receiving an error with TypeScript 2.6 because Hospital.vets is missing it's generic type. Why is this? In theory each vet in the vets array might look after a different type of Animal. As a Hosptial all I know is that each Vet must meet the constraint .

TypeScript playground

Upvotes: 1

Views: 89

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249466

You need to specify the generic parameter of the array item. You can use the base class Animal

interface Animal {}

class Dog implements Animal { }
class Cat implements Animal { }

class Vet<T extends Animal> {
    waitingList: T[];
}

class Hospital {
    vets: Vet<Animal>[] = [ new Vet<Dog>(), new Vet<Cat>() ]
}

Just a word of warning, depending on how you use this, it may let some errors slip through the type checker:

new Hospital().vets[0].waitingList.push(new Cat())

In the example above new Hospital().vets[0] is a Vet<Dog> but since we use Vet<Animal> we can also push a Cat, which may cause runtime errors.

Upvotes: 2

Related Questions