What are union types in TypeScript?
Why Interviewers Ask This
This is a classic screening question for TypeScript roles. Hiring managers ask it early in interviews to gauge your baseline understanding and determine if you can communicate technical concepts clearly.
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.
Pro Tip
This topic has TypeScript-specific nuances that differ from general programming. Highlighting those nuances in your answer shows expertise rather than generic knowledge.
Previous
What is the difference between interface and type alias in TypeScript?
Next
What are intersection types in TypeScript?