Skip to content

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: 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}`;
} }

This makes complex state modeling and data handling more robust and maintainable, with TypeScript helping to catch errors at compile time rather than runtime.

Create tagged unions using matchboxFactory to define unions of any type, or using defineStates to create states for use with state machines.