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
typeResult= {
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
functionhandleResult(result:Result):string
handleResult(
result: Result
result:
typeResult= {
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
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.