[英]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:然后:
typeof
in typeof currencies
.typeof
中typeof currencies
。number
, so MyArray[number]
gets all members of that array as a union.number
索引,因此MyArray[number]
将该数组的所有成员作为联合获取。value
property, you can drill into that to get a union of all possible types at that value
property.value
属性,您可以深入研究该属性以获取该value
属性的所有可能类型的联合。"USD" | "EU"
"USD" | "EU"
"USD" | "EU"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.