On this Page
On this Guide
- Lesson 01: What is TypeScript and Why Use It
- Lesson 02: Setting Up TypeScript in Your Project
- Lesson 03: Basic Types and Type Annotations
- Lesson 04: Functions and Type Inference
- Lesson 05: Objects, Interfaces, and Optional Properties
- Lesson 06: Arrays, Tuples, and readonly
- Lesson 07: Union, Intersection, and Literal Types
What is a Union Type?
A union type allows a value to be one of several types:
let input: string | number;
input = "hello";
input = 42;
Useful when a variable can take on multiple, known types.
Literal Types
Literal types are string, number, or boolean values themselves as types:
type Status = "success" | "error" | "loading";
let state: Status = "success";
Theyβre perfect for enums, flags, and discriminated unions.
Type Narrowing with Unions
TypeScript smartly narrows the type based on runtime checks:
function printLength(value: string | string[]) {
if (typeof value === "string") {
return value.length;
} else {
return value.join(", ").length;
}
}
This is called type narrowing β a core TypeScript feature.
What is an Intersection Type?
An intersection type combines multiple types into one:
type Timestamped = { createdAt: Date };
type User = { name: string };
type TimestampedUser = User & Timestamped;
const user: TimestampedUser = {
name: "Sam",
createdAt: new Date(),
};
All required fields from both types must be present.
Combining Unions and Intersections
You can build flexible and strict structures:
type Response =
| { status: "success"; data: string }
| { status: "error"; error: string };
Or combine behaviors:
type Loggable = { log: () => void };
type Savable = { save: () => void };
type Logger = Loggable & Savable;
Summary
- Use union types to allow multiple possible types
- Use literal types for specific value constraints
- Use intersection types to merge multiple types into one
- Leverage type narrowing with
typeof,in, andinstanceoffor safety
Up next: Type Aliases vs Interfaces β when to use each and why.