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.
Code
// 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
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
FAQ
- Is anything beyond the standard library required?
- Nothing beyond the standard library — the snippet is dependency-free.
Report a problem with this exampleOpens a pre-filled issue on GitHub.