Lets say i have an interface Animal, and i want it to have some general properties, and then either be a cat or a dog and have corresponding properties.
interface Dog {
dog: { sound: string; }
}
interface Cat {
cat: { lives: number; }
}
type CatOrDog = Cat | Dog;
interface Animal {
weight: number;
// index type of CatOrDog
}
So i was thinking
interface Animal {
weight: number;
[K in keyof CatOrDog]: CatOrDog[K];
}
But TypeScript gets very angry when i use anything else than the [K:string]: type
What i am trying to achieve is
// Success
const dog = <Animal> {
weight: 5,
dog: {sound: "woof" }
}
// Error, lives doesn't exist on Dog
const errorAnimal = <Animal> {
weight: 5,
dog: {sound: "woof" },
cat: { lives: 9 }
}
Also, if i wanted to add more index types, would that be possible?