- 01Getting Started
- 02Your First Output (console.log)
- 03Variables and Type Annotations (number/string/boolean)
- 04Array Types
- 05Function Types (Parameters and Return Values)
- 06Optional Parameters and Default Parameters
- 07Interfaces (interface)
- 08Optional Properties (?)
- 09Type Aliases (type)
- 10Union Types
- 11Literal Types
- 12enum (Enumerated Types)
- 13Classes and Types
- 14Inheritance (extends) and Implementing an Interface (implements)
- 15Generics (<T>)
- 16Tuple Types
- 17The any and unknown Types
- 18Type Assertions (as)
- 19The readonly Modifier
- 20[Applied] Build a Mini Inventory Management System
Union Types
This lesson covers union types, used to express "one of several possible types." It's for anyone searching "TypeScript union type usage."
Writing TypeA | TypeB expresses "either TypeA or TypeB." For example, number | string means "a number or a string."
The example builds a function, function formatId(id: number | string): string, that checks the actual type with typeof before branching its logic. This pattern โ checking a type before branching โ is called a type guard.
A common early mistake is calling a method that only exists on one of the possible types directly on a union-typed variable. You need to narrow the type first, with something like typeof or instanceof, before using it.
In real projects, union types are used a lot when an API response can take multiple shapes โ like "data on success, an error message on failure."
๐งช This site can't compile or run TypeScript directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ nothing is sent anywhere).
