A union type describes a value that can be one of several types, specified using the vertical bar (|) operator.
When working with union types, TypeScript requires you to narrow the broad union down to a specific type before calling type-specific methods.
flowchart TD
A["Input: string | number"] --> B{"typeof value == 'string'?"}
B -- "True" --> C["Branch: value.toUpperCase() (String Methods Available)"]
B -- "False" --> D["Branch: value.toFixed(2) (Number Methods Available)"]
// Basic Union Type
type ResultId = string | number;
function formatIdentifier(id: ResultId): string {
if (typeof id === "string") {
// TypeScript automatically narrows id to string inside this block
return `ID-STR-${id.toUpperCase()}`;
} else {
// TypeScript automatically narrows id to number inside this block
return `ID-NUM-${id.toFixed(0)}`;
}
}
// Discriminated Union (Tagged Union Pattern)
interface SuccessResponse {
kind: "success";
data: string[];
}
interface ErrorResponse {
kind: "error";
errorMessage: string;
}
type ApiResponse = SuccessResponse | ErrorResponse;
function handleApiResponse(response: ApiResponse): void {
// Narrowing based on the discriminant 'kind' property
if (response.kind === "success") {
console.log(`Fetched ${response.data.length} records.`);
} else {
console.error(`API Failure: ${response.errorMessage}`);
}
}
handleApiResponse({ kind: "success", data: ["User1", "User2"] });
handleApiResponse({ kind: "error", errorMessage: "Unauthorized 401" });
kind, type, status) to distinguish union members cleanly.in Operator for Object Narrowing: Check for property existence (if ("errorMessage" in response)) when narrowing objects without discriminant tags.Create a union type StringOrArray that accepts string | string[]. Write a function that prints the string's length if it's a string, or the array count if it's an array.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With