OneOf: exclusive unions
A union in TypeScript does not forbid mixing its members. A mapped utility type makes the members mutually exclusive.
- #typescript
- #patterns
- #type-level
A | B means assignable to at least one of these, not exactly one of these.
A value carrying the fields of both members satisfies it:
Excess property checking hides this for a fresh object literal. It stops applying the moment the value arrives through a variable, a parse or an API response, which is where it matters.
OneOf fixes the union itself by giving each member an optional never for
every key it does not declare, so a foreign key has no type it could hold:
const car: … = raw
| Value | Electric | Petrol | OneOf<Electric | Petrol> |
|---|---|---|
battery only{ name: "x", batteryKwh: 75 } | accepted | accepted |
tank only{ name: "x", tankLitres: 50 } | accepted | accepted |
mixes both variants{ name: "x", batteryKwh: 75, tankLitres: 50 }
| accepted | rejected |
Implementation
It is two type aliases, in one-of.ts:
AllKeys has to be a defaulted type parameter rather than an inline
computation. Members extends unknown distributes over the union, and inside
the distribution Members is a single member, so keyof Members no longer
sees the others. The parameter list resolves the key set before distribution
begins.
KeysOfUnion exists for the same reason. keyof (Electric | Petrol) gives
only the keys the members share, which is the wrong set.
Cost
- Error messages get worse. A mixed object reports a
never-typed property, not you mixed two variants. In a wide union the reader has to work out which member the compiler picked. - It takes an interface, not a discriminated union. If the members already
carry a shared literal tag, use that instead.
switchnarrowing, exhaustiveness checks and the error messages are all better. - Excess keys stay forbidden downstream.
Partial<Record<K, never>>means absent orundefined, so{ ...petrol, batteryKwh: undefined }passes whilebatteryKwh: 0does not. A partial update that spreads a real value for the wrong key fails to compile.
Use it when the variants have no tag to discriminate on: message shapes parsed from an API response, mutually exclusive component props, a config object where exactly one backend is set.
Related entries
- Type-safe result pattern. The discriminated-union alternative, for when the variants can carry a tag.
Files in this entry
Saved beside the document, and served as-is.
Related entries
Type-safe result pattern
Error handling in TypeScript through a discriminated union instead of a thrown exception.
Compound components
Expose a component's internals as named subcomponents that share state through a private context.
Render props
Hand rendering control to the caller through a function child, and when a hook is the better answer.