Introduction
Type-safe discriminated unions for TypeScript. Define once — get constructors, type guards, exhaustive matching, async dispatch, and runtime validation.
dismatch is a small (~1.1 kB gzipped, zero dependencies) library that turns
discriminated unions into a complete toolkit: constructors, type guards,
exhaustive pattern matching, partial transforms, fold-based aggregation,
async dispatch, and runtime validation — all generated from a single schema.
import { createUnion, is, type InferUnion } from 'dismatch';
const Shape = createUnion({
circle: (radius: number) => ({ radius }),
rectangle: (width: number, height: number) => ({ width, height }),
});
type Shape = InferUnion<typeof Shape>;
const area = Shape.match({
circle: ({ radius }) => Math.PI * radius ** 2,
rectangle: ({ width, height }) => width * height,
});
area(Shape.circle(5)); // 78.54
switchgives you exhaustiveness.dismatchgives you exhaustiveness plus reusable typed matchers,map,fold,partition,count,is, runtime validation, and async — all from a single schema.
What sets it apart
- No runtime wrappers.
createUnionproduces plain{ type, ... }objects, so values cross network boundaries, debug cleanly, and interop withswitch/ts-patternwithout unwrapping. See Removing dismatch for the exit path. - Reusable handlers.
match,map,foldreturn typed functions you can pass toarray.map,pipe, or store in a variable. Other libraries make every match one-shot. - Variant-aware collections.
count,partition,foldoperate on whole arrays in a single pass, with both branches narrowed. - First-class async.
matchAsync,matchAllAsync,foldAsyncand friends returnPromise<R>— neverPromise<A> | Promise<B>— and freely mix sync handlers. - Runtime safety.
isKnownvalidates incoming data against the declared schema;UnknownVariantErrorcarries.variantand.knownfor clean reporting. - Companion
RemoteData. A ready-madeIdle | Loading | Refreshing | Ok | Failedunion for async UI state, usable with every dismatch API.
Where to go next
- Brand new? Read Getting Started and the Discriminated Unions primer.
- Already comfortable with DUs? Jump to Standalone
API or
createPipeHandlers. - Building UI for async data? See RemoteData and Async APIs.
- Want a side-by-side with other libraries? See Comparison.