TypeScript Developer interview question · Most asked
What are union types and how do you work with them safely?
Summary
A union type (A | B) describes a value that can be one of several types. You can only use members common to all variants until you narrow the value with checks.
Longer Answer
Unions model real-world variability: string | number IDs, 'asc' | 'desc' options, or API results. Narrow with typeof, discriminants or guards before using variant-specific members.
Key Points
A | B= one of several types- Only shared members usable before narrowing
- Literal unions replace magic strings
More most-asked TypeScript Developer questions
- Explain `any`, `unknown` and `never`.
- What are the differences between `interface` and `type` aliases?
- What is structural typing in TypeScript?
- What is type narrowing and what techniques does TypeScript support?
- What are discriminated unions and why are they powerful?
- What are generics and how do constraints work?
- Which built-in utility types do you use most, and what do they do?
- What is TypeScript and what problems does it solve?