Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get union type from indexed object values

Tags:

typescript

Say I have an indexed type:

type X = {
 a: 'A',
 b: 'B'
}

is it possible to get (derived) from it:

type V = 'A' | 'B'

not using explicit method like:

type V = X['a'] | X['b']

What I want is something like keyof (for getting keys union type), but for values.

like image 586
WHITECOLOR Avatar asked Apr 26 '18 13:04

WHITECOLOR


2 Answers

You can use a type query with the result of keyof:

type V = X[keyof X]

Generally a type query will return a union of all possible field types, so X['a'] | X['b'] is the same as X['a' | 'b']. This is why X[keyof X] works, as keyof will return a union of string literal types representing all keys in the object.

like image 58
Titian Cernicova-Dragomir Avatar answered Nov 04 '22 05:11

Titian Cernicova-Dragomir


I realize this has already been answered but if you are here from google and you are looking for a way to also convert an objects values to a union (as the title of the question suggests), you can do this:

const X = {
 a: 'A',
 b: 'B'
 // mark properties as readonly, otherwise string type inferred 
} as const

type XValues = typeof X[keyof typeof X]

// "A" | "B
like image 36
lfender6445 Avatar answered Nov 04 '22 06:11

lfender6445