Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collapsing a discriminated union - derive an umbrella type with all possible key-value combinations from the union

I have a discriminated union, for example:

type Union = { a: "foo", b: string, c: number } | {a: "bar", b: boolean }

I need to derive a type that includes all potential properties, assigned with types that may be found on any member of Union, even if only defined on some - in my example:

type CollapsedUnion = { 
  a: "foo" | "bar", 
  b: string | boolean, 
  c: number | undefined 
}

How can I make a generic that derives such collapsed unions?
I need a generic that supports unions of any size.

Similar behaviour can be achieved as a byproduct by using native Omit utility, but unfortunately for me it leaves out properties that are not present on every union memeber (does not count them in as undefined or via ?).

like image 332
Michal Kurz Avatar asked Jan 16 '21 14:01

Michal Kurz


People also ask

How to discriminate one type from the other in a union?

A solution is using a combination of string literal types, union types , type guards, and type aliases. To discriminate one type from the other in a union, we add a __typename property for that goal.

Is it possible to create a discriminated union for shape in C #?

C# has been adding a lot of functional features over the last few years. So, we are going to achieve something close to that in C# using Records and Inheritance. In F#, we can create a Discriminated Union for Shape as shown below.

What is the difference between as operator and discriminated union in JavaScript?

The as operator demands to import all of the type definitions just for making the assertion adding unnecessary dependencies to our code. Discriminated Unions combine more than one technique and create self-contained types. Types that carry all the information to use them without worrying about name collisions or unexpected changes.

What is the purpose of a discriminated union?

Discriminated unions provide support for values that can be one of a number of named cases, possibly each with different values and types. Discriminated unions are useful for heterogeneous data; data that can have special cases, including valid and error cases; data that varies in type from one instance to another;


2 Answers

I found a two way(s)!

EDIT: this is a solution with two separate type parameters. See lower down for a solution with a single union type parameter.

// The source types
type A = { a: "foo", b: string, c: number }
type B = { a: "bar", b: boolean }

// This utility lets T be indexed by any (string) key
type Indexify<T> = T & { [str: string]: undefined; }

// Where the magic happens ✨
type AllFields<T, R> = { [K in keyof (T & R) & string]: Indexify<T | R>[K] }

type Result = AllFields<A, B>
/**
 * 🥳
 * type Result = {
 *   a: "foo" | "bar";
 *   b: string | boolean;
 *   c: number | undefined;
 * }
 */

How it works

AllFields is a mapped type. The 'key' part of the mapped type

[K in keyof (T & R) & string]

means that K extends the keys of the union T & R, which means it will be a union of all the keys that are either in T or in R. That's the first step. It ensures that we are making an object with all the required keys.

The & string is necessary as it specifies that K also has to be a string. Which is almost always going to be the case anyway, as all object keys in JS are strings (even numbers) – except for symbols, but those are a different kettle of fish anyway.

The type expression

Indexify<T | R>

returns the union type of T and R but with string indexes added in. This means that TS won't throw an error if we try to index it by K even when K doesn't exist in one of T or R.

And finally

Indexify<T | R>[K]

means that we are indexing this union-with-undefineds-for-string-indexes by K. Which, if K is a key of either T, R, or both, will result in that key's value type(s).

Otherwise, it will fall back to the [string]: undefined index and result in a value of undefined.

Here's a playground link


EDIT: solution for a single generic parameter

You specified that you don't actually want this to work for two type parameters, but with an existing union type, regardless of how many members are in the union.

It took blood, sweat and tears but I've got it.

// Magic as far as I'm concerned.
// Taken from https://stackoverflow.com/a/50375286/3229534
type UnionToIntersection<U> =
  (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never

// This utility lets T be indexed by any key
type Indexify<T> = T & { [str: string]: undefined; }

// To make a type where all values are undefined, so that in AllUnionKeys<T>
// TS doesn't remove the keys whose values are incompatible, e.g. string & number
type UndefinedVals<T> = { [K in keyof T]: undefined }

// This returns a union of all keys present across all members of the union T
type AllUnionKeys<T> = keyof UnionToIntersection<UndefinedVals<T>>

// Where the (rest of the) magic happens ✨
type AllFields<T> = { [K in AllUnionKeys<T> & string]: Indexify<T>[K] }


// The source types
type A = { a: "foo", b: string, c: number }
type B = { a: "bar", b: boolean; }

type Union = A | B

type Result = AllFields<Union>
/**
 * 🥳
 * type Result = {
 *   a: "foo" | "bar";
 *   b: string | boolean;
 *   c: number | undefined;
 * }
 */

I got UnionToIntersection from a brilliant answer by @jcalz. I've tried to understand it but can't. Regardless, we can treat it as a magic box that transforms union types into intersection types. That's all we need to get the result we want.

New TS playground link

like image 153
Aron Avatar answered Sep 27 '22 23:09

Aron


It is doable; one possible solution is presented below. I would be interested if it is possible to achieve it in a simpler way. I added comments to walk you through the code.

// an axiliary type -- we need to postpone creating a proper union, as a tuple type can be traversed recursively
// I added additional branch to make the task a bit harder / to make sure it works in a more generic case
type ProtoUnion = [{ a: "foo", b: string, c: number }, {a: "bar", b: boolean }, { c: string }]

// an axiliary type to recover proper Union
type CollapseToUnion<T extends Record<string, any>[], Acc = {}> = // starting with a tuple of records and accumulator
  T extends [infer H, ...infer Rest] ? // traverse
    Rest extends Record<string, any>[] ? // if still a record present
      CollapseToUnion<Rest, (H | Acc)> : // recursive call: collapse as union
        // in other cases return accumulator 
        Acc : 
          Acc

// union recovered
type Union = CollapseToUnion<ProtoUnion>

// this type is empty, so starting with union is _impossible_ to recover all needed keys in a generic way 
type UnionKeys = keyof Union 

// this type achieves what you are asking for but only for 2 types
type MergeAsValuesUnion<A, B> = { [K in (keyof A | keyof B)]: 
    K extends keyof A ? 
      K extends keyof B ? A[K] | B[K] : 
        A[K] | undefined :
          K extends keyof B ? B[K] | undefined :
            never
  }

type OriginalUnionIntersected = MergeAsValuesUnion<ProtoUnion[0], ProtoUnion[1]>
/*
type OriginalUnionIntersected = {
    a: "foo" | "bar";
    b: string | boolean;
    c: number | undefined;
}
*/


// this is works exactly the same as CollapseToUnion, but instead of reducing with | 
// it uses MergeAsValuesUnion to reduce
type CollapseToIntersetion<T extends Record<string, any>[], Acc = {}> = T extends [infer H, ...infer Rest] ?
  Rest extends Record<string, any>[] ?
    CollapseToIntersetion<Rest, MergeAsValuesUnion<H, Acc>> 
    : Acc : Acc


const i: CollapseToIntersetion<ProtoUnion> = {
  a: 'bar', // "bar" | "foo" | undefined
  b: true, // string | boolean | undefined
  c: undefined // string | number | undefined
}

EDIT:

CollapseToIntersetion was bit off. Starting with {} as a default accumulator results in having | undefined in value types.

// this is works exactly the same as CollapseToUnion, 
// but instead of reducing with | -- it uses MergeAsValuesUnion to reduce; 
// Acc = T[0] since Acc = {} would result in all values types unioned with undefined
type CollapseToIntersetion<T extends Record<string, any>[], Acc = T[0]> = T extends [infer H, ...infer Rest] ?
  Rest extends Record<string, any>[] ?
    CollapseToIntersetion<Rest, MergeAsValuesUnion<H, Acc>> 
    : Acc : Acc

PLAYGROUND

like image 38
artur grzesiak Avatar answered Sep 28 '22 01:09

artur grzesiak