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.
What are Tagged Unions?
Section titled “What are Tagged Unions?”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: string
data: string }
| { status: "error"
status: "error"; message: string
message: string };
// Using the tagged union
function function handleResult(result: Result): string
handleResult(result: Result
result: type Result = {
status: "success";
data: string;
} | {
status: "error";
message: string;
}
Result) {
switch (result: Result
result.status: "success" | "error"
status) {
case "success":
// TypeScript knows result.data exists here
return result: {
status: "success";
data: string;
}
result.data: string
data.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: string
message}`;
}
}
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.
📦 matchboxFactory Create type-safe tagged union factories with pattern matching
🔧 defineStates Define state machines with type-safe tagged unions