Suppose I have the following interface X
:
type X = {
red: number,
blue: string
}
Is it possible to construct a union type Y
using mapped types? If not, can it be constructed with other kind of type-level mechanisms?
type Y = {
kind: "red"
payload: number
} | {
kind: "blue"
payload: string
}
Yes, you can make use of the fact that T[keyof T]
is a union of the values of T
, whatever T
is. You can use a mapped type to construct a type whose values are the branches of the union you want:
type Y = { [K in keyof X]: {kind: K, payload: X[K]} }[keyof X]
Playground Link
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