Skip to main content
Module

x/scaffold/src/deps/types.ts>UnionToIntersection

scaffold your next project with style and 💗
Latest
type alias UnionToIntersection
import { type UnionToIntersection } from "https://deno.land/x/scaffold@0.3.0/src/deps/types.ts";

Convert a union type to an intersection type using distributive conditional types.

Inspired by this Stack Overflow answer.

Examples

Example 1

import type {UnionToIntersection} from 'type-fest';

type Union = {the(): void} | {great(arg: string): void} | {escape: boolean};

type Intersection = UnionToIntersection<Union>;
//=> {the(): void; great(arg: string): void; escape: boolean};

A more applicable example which could make its way into your library code follows.

Example 2

import type {UnionToIntersection} from 'type-fest';

class CommandOne {
	commands: {
		a1: () => undefined,
		b1: () => undefined,
	}
}

class CommandTwo {
	commands: {
		a2: (argA: string) => undefined,
		b2: (argB: string) => undefined,
	}
}

const union = [new CommandOne(), new CommandTwo()].map(instance => instance.commands);
type Union = typeof union;
//=> {a1(): void; b1(): void} | {a2(argA: string): void; b2(argB: string): void}

type Intersection = UnionToIntersection<Union>;
//=> {a1(): void; b1(): void; a2(argA: string): void; b2(argB: string): void}
definition: (Union extends unknown ? (distributedUnion: Union) => void : never) extends ((mergedIntersection: infer Intersection) => void) ? Intersection : never