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 }[]
.
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.
What would be the right way to define these types so I can enforce that currency
holds a valid currency value?
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
.
Then:
typeof
in typeof currencies
.number
, so MyArray[number]
gets all members of that array as a union.value
property, you can drill into that to get a union of all possible types at that value
property."USD" | "EU"
"USD" | "EU"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.