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.

TypescriptConfig Management

Code

typescriptsnippet
15 lines
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: '[email protected]' };
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: '[email protected]', handle: '@ops' };
console.log('both rejected at compile time');

Output

Captured from a sandboxed run of this snippet in the build pipeline.

[email protected] @ops-team
both rejected at compile time

What 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

FAQ

Is the dependency story complicated?
Not at all: zero dependencies, so there is nothing to version or audit.