简体   繁体   English

根据对象数组的值定义 TypeScript 类型

[英]Define a TypeScript type from the values of an object array

Given the following array:给定以下数组:


type Currency = {
  text: string,
  value: string
}

let currencies: Currency[] = [ 
  { text: 'American dollars', value: 'USD' },
  { text: 'Euros', value: 'EU' }
]

These currencies might come from a database or a web service, but will have that shape, that is: { text: string, value: string }[] .这些货币可能来自数据库或网络服务,但具有这种形状,即: { text: string, value: string }[]

Is there some way to define a variable like this:有没有办法定义这样的变量:

let currency: 'USD' | 'EU'

That is, a type which should be the value property of one item of the currencies array.也就是说,一种类型应该是currencies数组的一项的值属性。

What would be the right way to define these types so I can enforce that currency holds a valid currency value?定义这些类型的正确方法是什么,以便我可以强制currency持有有效的货币价值?

Sure can.当然可以。

const currencies = [ 
  { text: 'American dollars', value: 'USD' },
  { text: 'Euros', value: 'EU' }
] as const

type CurrencyName = (typeof currencies)[number]['value'] // "USD" | "EU"

let currency: CurrencyName = 'USD' // works

First of all, currencies needs to be a const and as const this tells typescript that these are constant literals and not just any old string .首先, currencies需要是一个const并且as const这告诉打字稿这些是常量文字,而不仅仅是任何旧的string

Then:然后:

  • You can get the type of a value with typeof in typeof currencies .你可以得到一个值的类型typeoftypeof currencies
  • This is an array.这是一个数组。 Array's are indexed by number , so MyArray[number] gets all members of that array as a union.数组由number索引,因此MyArray[number]将该数组的所有成员作为联合获取。
  • All union members have a value property, you can drill into that to get a union of all possible types at that value property.所有联合成员都有一个value属性,您可以深入研究该属性以获取该value属性的所有可能类型的联合。
  • The result is "USD" | "EU"结果是"USD" | "EU" "USD" | "EU"

Playground 操场

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

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