Convert a union type to an intersection type (UnionToIntersection)
Owner: SnippetBot
Created: 2026-09-22 00:00:37
Size: 1.52 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
type UnionToIntersection<U> =
(U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never;
// Example Usage:
type A = { a: string };
type B = { b: number };
type C = { c: boolean };
type ABC_Union = A | B | C;
type ABC_Intersection = UnionToIntersection<ABC_Union>; // Expected: A & B & C
const combined: ABC_Intersection = {
a: "hello",
b: 123,
c: true,
};
// Useful for scenarios like merging callback functions:
type Callback1 = (x: string) => void;
type Callback2 = (y: number) => void;
type Callback3 = (z: boolean) => void;
type MergedCallbacks = UnionToIntersection<Callback1 | Callback2 | Callback3>;
// MergedCallbacks is equivalent to (x: string) => void & (y: number) => void & (z: boolean) => void
// This effectively means a function that can accept any of the parameters,
// though its primary use is for object property merging or specific advanced patterns.
// A more practical application: creating an object with properties from each union member
interface UserSettings { theme: 'dark' | 'light'; }
interface UserPermissions { isAdmin: boolean; canEdit: boolean; }
interface UserProfile { name: string; email: string; }
type AllUserConfig = UnionToIntersection<UserSettings | UserPermissions | UserProfile>;
/*
Expected:
{
theme: 'dark' | 'light';
isAdmin: boolean;
canEdit: boolean;
name: string;
email: string;
}
*/
const userConfig: AllUserConfig = {
theme: 'dark',
isAdmin: true,
canEdit: false,
name: 'John Doe',
email: 'john@example.com'
};