Union To Intersection Merges Option Sets

Flip a union of option objects into an intersection through contravariant function positions, so merged option sets require every member.

TypescriptConfig Management

Code

typescriptsnippet
18 lines
// A union of option objects becomes an intersection: every member's keys
// must be present at once. The contravariant function position flips the
// union, and a second inference round extracts it.
type UnionToIntersection<U> = (U extends unknown ? (arg: U) => void : never) extends (
  arg: infer I,
) => void
  ? I
  : never;

type ServerOptions = { retries: number } | { timeoutMs: number };
type Merged = UnionToIntersection<ServerOptions>;

const merged: Merged = { retries: 3, timeoutMs: 1_500 };
console.log(merged.retries, merged.timeoutMs);

// Without the helper, a plain union accepts any single member alone
const loose: ServerOptions = { retries: 3 };
console.log('union accepts partial:', 'retries' in loose && !('timeoutMs' in loose));

How it works

Module-level object literal, fixed keys: retries.

Using it

The run emits 1 labeled section — union accepts partial: — one per step.

Output is labeled for readability — expect lines prefixed with union accepts partial:.

Key statements

type UnionToIntersection<U> = (U extends unknown ? (arg: U) => void : never) extends (
  arg: infer I,
) => void

Interactive Tools for This Topic

FAQ

Is anything beyond the standard library required?
Nothing beyond the standard library — the snippet is dependency-free.