Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to create a discriminated union using mapped types in TypeScript?

Tags:

typescript

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
}
like image 585
Wong Jia Hau Avatar asked Sep 05 '25 03:09

Wong Jia Hau


1 Answers

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

like image 66
kaya3 Avatar answered Sep 07 '25 22:09

kaya3