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}`;
}
}
This makes complex state modeling and data handling more robust and maintainable, with TypeScript helping to catch errors at compile time rather than runtime.
Tagged Unions in Matchina
Section titled “Tagged Unions in Matchina”Create tagged unions using matchboxFactory
to define unions of any type, or using defineStates
to create states for use with state machines.
📦 matchboxFactory Create type-safe tagged union factories with pattern matching
🔧 defineStates Define states as matchbox factories