简体   繁体   中英

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 }[] .

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:

  • You can get the type of a value with typeof in typeof currencies .
  • This is an array. Array's are indexed by number , so MyArray[number] gets all members of that array as a union.
  • All union members have a value property, you can drill into that to get a union of all possible types at that value property.
  • The result is "USD" | "EU" "USD" | "EU"

Playground

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.

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