Distributive Conditional Types Split Unions

Naked type parameters in conditional types evaluate each union member and rebuild the union; tuple-wrapping the parameter disables the split.

TypescriptData Integrity

Code

typescriptsnippet
33 lines
// A naked type parameter inside a conditional type evaluates per union member -
// that is distribution; the results reassemble into a union
type FieldError = { kind: 'missing'; field: string };
type StatusError = { kind: 'http'; status: number };
type RequestError = FieldError | StatusError;

type Tagged<T> = T extends { kind: infer K } ? { errorKind: K; error: T } : never;

// Each member gets its own errorKind literal (distribution active)
type TaggedErrors = Tagged<RequestError>;

// Proof distribution is on: errorKind and error must come from the same member - mixing is a compile error
// const mismatch: TaggedErrors = { errorKind: 'missing', error: { kind: 'http', status: 500 } };

const tagged: TaggedErrors[] = [
  { errorKind: 'missing', error: { kind: 'missing', field: 'email' } },
  { errorKind: 'http', error: { kind: 'http', status: 503 } },
];
for (const t of tagged) console.log(`${t.errorKind}: ${t.error.kind}`);

// Wrapping the type parameter in a tuple turns distribution off: the union evaluates once as a whole
type Whole<T> = [T] extends [unknown] ? { all: T } : never;
type Wrapped = Whole<RequestError>;

// Proof it is off: all accepts the entire union (a compile error while distribution is on)
const either: RequestError = { kind: 'http', status: 418 };
const single: Wrapped = { all: either };
console.log('whole wrapper holds union:', single.all.kind);

// never distributes to never: an empty union has no members to enumerate
type Empty = Tagged<never>;
const emptyIsNever: Empty extends never ? true : false = true;
console.log('empty union stays never:', emptyIsNever);

Output

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

missing: missing
http: http
whole wrapper holds union: http
empty union stays never: true

Inside the snippet

Repetition is confined to for (const t of tagged) console.log(${t.errorKind}: ${t.error.kind}); — the rest of the file is straight-line.

The top-level object literal pins kind, status as plain values — no derivation, no imports behind them.

Using it

The demo output is labeled (whole wrapper holds union:, empty union stays never:), so each printed line points back to the operation it originated from.

Key statements

type Tagged<T> = T extends { kind: infer K } ? { errorKind: K; error: T } : never;

Interactive Tools for This Topic

FAQ

Do I need to install anything before running this?
No — every API used here ships with the language runtime, so there is nothing to install.