Imagine having an interface called Animal, with some general properties, and then either be a cat or a dog with corresponding properties.
interface Dog {
dog: { sound: string; }
}
interface Cat {
cat: { lives: number; }
}
type CatOrDog = Cat | Dog;
interface Animal {
weight: number;
// index type of CatOrDog
}
I came up with this idea
interface Animal {
weight: number;
[K in keyof CatOrDog]: CatOrDog[K];
}
However, TypeScript throws errors when trying to use something other than [K:string]: type
The goal 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 }
}
Can more index types be added if needed?