Skip to content

Tagged Unions

The matchboxFactory function creates factories for working with tagged unions in TypeScript, providing type-safe pattern matching, exhaustiveness checking, and comprehensive type inference.

Tagged unions (also known as discriminated unions or sum types) are a powerful way to represent data that can be one of several distinct types, each with its own structure:

// A simple tagged union using TypeScript's native union types
type 
type Result = {
    status: "success";
    data: string;
} | {
    status: "error";
    message: string;
}
Result
=
| { status: "success"status: "success"; data: stringdata: string } | { status: "error"status: "error"; message: stringmessage: string }; // Using the tagged union function function handleResult(result: Result): stringhandleResult(result: Resultresult:
type Result = {
    status: "success";
    data: string;
} | {
    status: "error";
    message: string;
}
Result
) {
switch (result: Resultresult.status: "success" | "error"status) { case "success": // TypeScript knows result.data exists here return
result: {
    status: "success";
    data: string;
}
result
.data: stringdata.String.toUpperCase(): string
Converts all the alphabetic characters in a string to uppercase.
toUpperCase
();
case "error": // TypeScript knows result.message exists here return `Error: ${
result: {
    status: "error";
    message: string;
}
result
.message: stringmessage}`;
} }

How to Create a Tagged Union Matchbox Factory

Section titled “How to Create a Tagged Union Matchbox Factory”

Use matchboxFactory or defineStates, which calls matchboxFactory and uses key for its tag property.