2 Convert a union type to an intersection type using [distributive conditional types](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html#distributive-conditional-types).
4 Inspired by [this Stack Overflow answer](https://stackoverflow.com/a/50375286/2172153).
8 import {UnionToIntersection} from 'type-fest';
10 type Union = {the(): void} | {great(arg: string): void} | {escape: boolean};
12 type Intersection = UnionToIntersection<Union>;
13 //=> {the(): void; great(arg: string): void; escape: boolean};
16 A more applicable example which could make its way into your library code follows.
20 import {UnionToIntersection} from 'type-fest';
31 a2: (argA: string) => undefined,
32 b2: (argB: string) => undefined,
36 const union = [new CommandOne(), new CommandTwo()].map(instance => instance.commands);
37 type Union = typeof union;
38 //=> {a1(): void; b1(): void} | {a2(argA: string): void; b2(argB: string): void}
40 type Intersection = UnionToIntersection<Union>;
41 //=> {a1(): void; b1(): void; a2(argA: string): void; b2(argB: string): void}
44 export type UnionToIntersection<Union> = (
45 // `extends unknown` is always going to be the case and is used to convert the
46 // `Union` into a [distributive conditional
47 // type](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html#distributive-conditional-types).
49 // The union type is used as the only argument to a function since the union
50 // of function arguments is an intersection.
51 ? (distributedUnion: Union) => void
54 // Infer the `Intersection` type since TypeScript represents the positional
55 // arguments of unions of functions as an intersection of the union.
56 ) extends ((mergedIntersection: infer Intersection) => void)