Signature
Type Inference
taggedUnion() creates a discriminated union type:
Basic Usage
How It Works
Decoding happens in two steps:- Look at the discriminator field (e.g.
'type') in the incoming object - Based on that value, select the appropriate decoder from the mapping
vs either()
taggedUnion() is more performant and provides better error messages than either() for discriminated unions:
Performance
either(): Tries each decoder one by one until one succeedstaggedUnion(): Reads the discriminator once, then uses the correct decoder
taggedUnion() is significantly faster.
Error Messages
TypeScript Discriminated Unions
taggedUnion() works perfectly with TypeScript’s discriminated unions:
API Response Example
Custom Discriminator Field
The discriminator field name is configurable:Nested Tagged Unions
Implementation
Source: ~/workspace/source/src/unions.ts:150-163Related Functions
select(): A generalization oftaggedUnion()that works even if there isn’t a single discriminator field (see ~/workspace/source/src/unions.ts:174-182)either(): For general union types without a discriminatoroneOf(): For unions of scalar literal values
