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

← All TypeScript Developer questions