Home > database >  Typescript string union of object values as constants
Typescript string union of object values as constants

Time:10-29

If I have an array of objects, how can I get a property of each object and create string union of its constant value? For example, below I have the array options. I want to create a type like type Values = 'firstName' | 'lastName' | 'email'.

const options = [
  { label: 'First Name', value: 'firstName' }, 
  { label: 'Last Name', value: 'lastName' },
  { label: 'Email', value: 'email' }
] as const;

// Close, but not quite what I need
const values = options.map(x => x.value) // ("firstName"|"lastName"|"email")[]

CodePudding user response:

You'll be able to retrieve the type by using typeof and indexing into the array type with number:

type Values = (typeof values)[number];

Please note that typeof behaves differently when used in this context. It gets the type of a variable; in this case it's values that has a type of ("firstName" | "lastName" | "email")[].

Playground

  • Related