Example
const food = {
fruit: ['apples', 'oranges'],
meat: ['chicken', 'pig']
}
function makeFood(ingredient, category) {
switch(true) {
case category === 'fruit' && ingredient === 'apples' {
// do something
}
case category === 'fruit' && ingredient === 'oranges' {
// do something
}
case category === 'meat' && ingredient === 'chicken' {
// do something
}
case category === 'meat' && ingredient === 'pig' {
// do something
}
}
}
what's the best way to type category is a key of food and ingredient is a value?
Currently I'm doing
function(ingredient, keyof typeof category) {
would love to keep the relation between the two. So TS will know the ingredient type based in the category value.
category? How doingredientandcategoryrelate tofood?function f<T extends keyof typeof food>(ingredient: (typeof food)[T][number], category: T) {? Note, that unless you addas constto the arrays infood, they are juststring[]. Also note, that[number]may be a bit quick&dirty, there are alternatives.