Lets say I have 3 types:
type AllowedAnimals = "dog" | "cat";
type AnimalFoodMap = {
name: SomeDogFoodType;
cat: SomeCatFoodType;
}
type Config<T extends AllowedAnimals> = {
animal: T;
food: AnimalFoodMap[T];
}
When creating a single object the type of food gets inferred propperly:
const dog: Config = {
animal: "dog",
food: {} // <- type is correctly inferred as "SomeDogFoodType"
}
This all works fine like expected, the issue arrises when I want to make the Config type recursive by accepting children:
type Config<T extends AllowedAnimals> = {
animal: T;
food: AnimalFoodMap[T];
children?: Config[];
}
At this point the type inferrence for the prop food stops working and instead it becomes a union of type SomeDogFoodType | SomeCatFoodType:
const myConfig: Config = {
animal: "dog",
food: {} <- correctly inffered as "SomeDogFoodType"
children: [
{
animal: "cat",
food: {} <- inferred as "SomeDogFoodType | "SomeCatFoodType"
}
]
}
My goal is to infer the type of food correctly for each item in the array of children no matter how far down it is nested. What is the best way to achieve this?
Hope the example was clear, if not i can provide some others.