Typescript limit type combinations in class

70 Views Asked by At

I have a simple example:

interface IDog {
  bark: void;
  type: 'dog';
}
interface ICat {
  meow: void;
  type: 'cat';
}
type IAnimalType = 'cat' | 'dog';
type IAnimal = IDog | ICat;

class ContainsAnimal {
  animalType: IAnimalType;
  animal: IAnimal;

  sound() {
    if (this.animalType === 'dog') { this.animal.bark(); }
  }
}

This won't compile because the compiler doesn't know that animalType === 'dog' means that type of animal === IDog (and bark doesn't exist on ICat).

Is there a way I can limit class ContainsAnimal types so that animal.type and animalType always correspond to one another?

0

There are 0 best solutions below