简体   繁体   English

Typescript 参数到来自 object 的键和值

[英]Typescript parameters to keys and values from an object

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.所以 TS 会根据类别值知道成分类型。

You use typescript Generics .您使用 typescript Generics In this you wanted category to be generic parameter, which ingredient can then use.在此您希望category是通用参数,然后可以使用哪种成分。

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.您需要在源代码 object 上使用as const (参见此处),以确保它的特定字符串是其类型的一部分。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM