XOR Types Exclude Overlapping Fields
Build an XOR helper from mapped Exclude keys and never-typed optionals so two config branches stay selectable but can never both fill in.
Code
type Without<T, U> = { [K in Exclude<keyof T, keyof U>]?: never };
// XOR keeps A and B selectable but never together: never optionals
// poison overlapping keys so the two branches cannot both fill in
type XOR<A, B> = (Without<A, B> & B) | (Without<B, A> & A);
type Contact = XOR<{ email: string }, { handle: string }>;
const byEmail: Contact = { email: 'ops@example.com' };
const byHandle: Contact = { handle: '@ops-team' };
console.log(byEmail.email, byHandle.handle);
// @ts-expect-error - both fields together is the state XOR exists to prevent
const both: Contact = { email: 'a@b.c', handle: '@ops' };
console.log('both rejected at compile time');Output
Captured from a sandboxed run of this snippet in the build pipeline.
ops@example.com @ops-team
both rejected at compile timeWhat the code does
Module-level object literal, fixed keys: email.
What to watch for
- All behavior comes from the standard library; nothing is external.
Applying it
The demo output is labeled (both rejected at compile time), so the printed lines read as a trace of the operations that ran.
Statements that matter
type Without<T, U> = { [K in Exclude<keyof T, keyof U>]?: never };
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 the dependency story complicated?
- Not at all: zero dependencies, so there is nothing to version or audit.
Report a problem with this exampleOpens a pre-filled issue on GitHub.