TypeScript
Types & Interfaces
To describe the shape of objects, TypeScript gives you interface and type. Both work for object shapes; each has strengths.
Interfaces
interface User {
id: number;
name: string;
email?: string; // optional property
readonly createdAt: Date; // can't be reassigned
}
const user: User = { id: 1, name: "Priya", createdAt: new Date() };
Interfaces can extend other interfaces and support declaration merging (re-opening to add members):
interface Admin extends User {
role: "admin" | "superadmin";
}
Type aliases
type can describe object shapes too, but is more flexible — it can alias any type:
type ID = string | number; // union
type Point = { x: number; y: number };
type Coords = Point & { z: number }; // intersection
type vs interface
| Feature | interface | type |
|---|---|---|
| Object shapes | ✅ | ✅ |
| Extends / combine | extends | & |
| Unions | ❌ | ✅ |
| Declaration merging | ✅ | ❌ |
💡
Rule of thumb: use interface for object and class shapes; use type when you need unions, intersections, or other advanced type operations.
Literal and union types
type Status = "idle" | "loading" | "success" | "error";
let state: Status = "loading"; // ✅
let bad: Status = "done"; // ❌ not assignable
Literal unions are perfect for modeling a fixed set of allowed values — far safer than plain string.
Watch & Learn
A recommended video to watch alongside this chapter.
More “Types & Interfaces” videos on YouTube