BeCuriouzBeCuriouz

Learn something new every day

🔷 TypeScript
🧱

Extending & Composing: Building Types From Other Types

💡 Use extends to grow interfaces and & to intersect types — both let you compose new shapes from existing ones instead of duplicating fields.

Instead of repeating fields, TypeScript lets you build bigger types out of smaller ones. With interfaces, you use the extends keyword to inherit everything from a parent and add more:

ts
interface Animal {
  name: string;
}
interface Dog extends Animal {
  breed: string;
}
// Dog now requires BOTH name and breed
const d: Dog = { name: "Rex", breed: "Lab" };

With type aliases, you compose using the intersection operator &, which merges members from every type into one. A & B means "has everything in A and everything in B":

ts
type Timestamps = { createdAt: number };
type User = { id: string } & Timestamps;
// User requires id AND createdAt

The two approaches mix freely: an interface can extends a type alias, and a type can intersect an interface. A handy rule of thumb — extends is for interfaces and reads like inheritance, while & works on any types and reads like "add these together." Both let you reuse existing shapes rather than copy-pasting fields, so a change in the base flows to everything built on it.

🧱 Extending & Composing: Building Types From Other Types — BeCuriouz