TypeScript Lesson 6: Union Types & Type Aliases
Union types let a value be one of several types. Type aliases let you name complex types. Together they’re incredibly powerful.
Union Types
// Value can be string OR number
type ID = string | number;
const userId: ID = 1; // OK
const postId: ID = "abc-123"; // OK
// Literal union — only specific values allowed
type Status = "pending" | "active" | "inactive" | "banned";
type Direction = "north" | "south" | "east" | "west";
type LogLevel = "debug" | "info" | "warn" | "error";
let status: Status = "active"; // OK
status = "deleted"; // ❌ Error!
Type Aliases
// Alias for a complex object shape
type Point = { x: number; y: number };
type Rectangle = { topLeft: Point; bottomRight: Point };
// Alias for a function type
type EventHandler = (event: MouseEvent) => void;
type Predicate<T> = (value: T) => boolean;
// Alias for a union
type Result<T> = { success: true; data: T } | { success: false; error: string };
// Usage:
function fetchUser(id: number): Result<User> {
if (id > 0) return { success: true, data: { id, name: "Alice" } };
return { success: false, error: "Invalid ID" };
}
Intersection Types
// Combine multiple types (must have ALL properties)
type HasId = { id: number };
type HasName = { name: string };
type HasEmail = { email: string };
// User must have id, name, AND email
type User = HasId & HasName & HasEmail;
const user: User = { id: 1, name: "Alice", email: "a@b.com" }; // OK
const bad: User = { id: 1, name: "Bob" }; // ❌ Error: missing email
🏋️ Practice Task
Create a type-safe API response system. Type Result
💡 Hint: Use discriminated unions: if (result.status === “ok”) { result.data } else { result.message }