Define Typescript Type With Additional Attribute based on value of other attribute

Viewed 37

I'm a bit new to Typescript, and I'm trying to define some types. I have some base Animal types. I want my SuperAnimal type to have an extra attribute (let's just say Cape), but if and only if the type of the Animal is a bird. At the same time, all super animals should have a superpower attribute, regardless of their AnimalType. How do I do that? Example code provided below:

enum AnimalType {
  Cat = 'cat',
  Dog = 'dog',
  Lizard = 'lizard',
  Bird = 'bird',
}

type Animal = {
  type: AnimalType;
  name: string;
}

type SuperAnimal = Animal & {
  superpower?: string;
}

/* Things I tried but don't work
type SuperAnimal = Animal & {
  superpower?: string;
} & ( {
  type: AnimalType.Bird;
  cape: string;
});
*/

1 Answers

You can utilize the OR | in TypeScript. You can do something like this:

enum AnimalType {
  Cat = 'cat',
  Dog = 'dog',
  Lizard = 'lizard',
  Bird = 'bird',
}

type Animal = {
  type: AnimalType;
  name: string;
};

type SuperAnimalDefault = Animal & { superpower: string };
type SuperBird = SuperAnimalDefault & {
  type: AnimalType.Bird;
  cape: string;
};
type SuperCat = SuperAnimalDefault & {
  type: AnimalType.Cat;
  tail: string;
};

type SuperAnimal = SuperAnimalDefault | SuperBird | SuperCat;
Related