What are union types in TypeScript?
Answer
A union type allows a variable or parameter to hold one of several specified types, combined with the | operator. Example: let id: string | number; — id can be either a string or a number. function formatId(id: string | number): string { return String(id); }. Union types are particularly useful with literal types to create a set of allowed values: type Status = "active" | "inactive" | "pending";. When working with a union type, TypeScript requires you to handle all possible types before using type-specific operations — this is called type narrowing. Narrow using typeof: if (typeof id === "string") { id.toUpperCase(); }, with instanceof, or with a custom type guard. Discriminated unions use a common literal property to distinguish union members — the recommended pattern for complex unions.
Previous
What is the difference between interface and type alias in TypeScript?
Next
What are intersection types in TypeScript?