Home > other >  Typescript parameters to keys and values from an object
Typescript parameters to keys and values from an object

Time:11-25

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.

CodePudding user response:

You use typescript Generics. In this you wanted category to be generic parameter, which ingredient can then use.

You'll need to use as const (see here) on your source object to make sure it's specific string are part of its type.

const food = {
  fruit: ['apples', 'oranges'],
  meat: ['chicken', 'pig']
} as const // important to add "as const" here

function makeFood<
  K extends keyof typeof food // Generic parameter
>(
  ingredient: typeof food[K][number], // use K to lookup types for ingredient
  category: K // provide the key to to use here as K
) {
 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
   }
 }
}

makeFood('apples', 'fruit')
makeFood('pig', 'fruit') // type error

Playground

  • Related