Union Types
Values that can be one of several types
Introduction
In this lesson, you'll learn about union types in TypeScript. Coming from JavaScript, you already have a foundation for understanding this concept. We'll build on that knowledge while highlighting the key differences.
In JavaScript, you're familiar with values that can be one of several types.
TypeScript has its own approach to values that can be one of several types, which we'll explore step by step.
The TypeScript Way
Let's see how TypeScript handles this concept. Here's a typical example:
// TypeScript union types
function formatValue(value: string | number): string {
if (typeof value === "string") {
return value.toUpperCase();
}
if (typeof value === "number") {
return value.toFixed(2);
}
return String(value);
}
let id: string | number = "abc123";
id = 123; // allowed by union typeComparing to JavaScript
Here's how you might have written similar code in JavaScript:
// JavaScript handles multiple types at runtime
function formatValue(value) {
if (typeof value === "string") {
return value.toUpperCase();
}
if (typeof value === "number") {
return value.toFixed(2);
}
return String(value);
}
let id = "abc123"; // could be string or number
id = 123; // reassignment worksYou may be used to different syntax or behavior.
Union types use | to combine types
You may be used to different syntax or behavior.
TypeScript narrows types in conditional blocks
You may be used to different syntax or behavior.
Common for values that can be multiple types
Step-by-Step Breakdown
1. Declaring Union Types
Use the | operator to create a type that can be any of several types.
let value: string | number;
value = "hello"; // OK
value = 42; // OK
// value = true; // Error!2. Type Narrowing
TypeScript automatically narrows union types in conditional blocks.
function process(value: string | number) {
if (typeof value === "string") {
// TypeScript knows value is string here
return value.toUpperCase();
}
// TypeScript knows value is number here
return value.toFixed(2);
}3. Literal Types
Union types can include specific literal values.
type Direction = "north" | "south" | "east" | "west";
type HttpStatus = 200 | 400 | 404 | 500;
let dir: Direction = "north"; // OK
// dir = "up"; // Error!Common Mistakes
When coming from JavaScript, developers often make these mistakes:
- Union types use | to combine types
- TypeScript narrows types in conditional blocks
- Common for values that can be multiple types
Key Takeaways
- Unions allow values to be one of several types
- TypeScript narrows unions in conditionals
- Literal unions are powerful for constrained values