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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With