Home > Enterprise >  Typescript: Map union value to union of objects
Typescript: Map union value to union of objects

Time:02-02

Not a clue how to ask this well, so here is what I have and what I'm after:

Start:

type Initial = {
    foo: string | number
}

End:

type Final = {
    foo: string
} | {
    foo: number
}

I need a type using generics that I can put Initial into that will output Final.

Edit: (Mapping through multiple union values) Playground Link

CodePudding user response:

You can create such a type, that will take a key and a type and distribute over the type of that property:

type Initial = {
    foo: string | number,
    otherProp: string
}
type Id<T> = {} & { [P in keyof T]: T[P]}

type DistributeUnion<T, TKey extends keyof T> = 
  T[TKey] extends infer U  // Make a type parameter that contains T[TKey]
    ? U extends U // We then distribute over the union
      ? Id<Record<TKey, U> & Omit<T, TKey>> // Create a new type with just one union constituent from T[TKey], and the rest of the props in T
      : never
    : never;
type Final = DistributeUnion<Initial, 'foo'>

// type Final = {
//     foo: string;
//     otherProp: string;
// } | {
//     foo: number;
//     otherProp: string;
// }

Playground Link

  •  Tags:  
  • Related