Building shapes from shapes
Real systems model families of related shapes: every product listing has a title and a price, but a book also has an author and a shirt also has a size. Copy the shared properties into each interface by hand and the copies drift apart the first time someone edits only one of them. extends exists so shared structure is declared once and inherited everywhere.
Interfaces can extend other interfaces, inheriting all their properties:
interface Animal { name: string; } interface Dog extends Animal { breed: string; }
A Dog has both name and breed. This mirrors how you layered behavior with classes and prototypes in Advanced JavaScript, but purely at the type level.
There is a second way to name a type, the type alias:
type Point = { x: number; y: number };
For object shapes, type and interface are nearly interchangeable. The practical differences: interface can be extended and reopened, while type can also name things that are not objects at all, like unions (type Id = string | number), which interfaces cannot.
Code exercise · typescript
Run it. Dog gets name from Animal via extends, and Point is declared with a type alias. Then try creating a Dog without name to confirm the inherited property is required.
Quiz
Which of these can ONLY be written with a type alias, not an interface?
Code exercise · typescript
Your turn. Declare interface Vehicle with wheels (number), then interface Car extends Vehicle adding brand (string). Write describeCar(c: Car): string returning brand + " with " + wheels + " wheels", and print it for a Volvo with 4 wheels.
Combining shapes with &
The | of Unit 2 said "one of these". Its counterpart, the intersection type &, says "all of these at once":
type Named = { name: string }; type Timestamped = { createdAt: number }; type Post = Named & Timestamped & { body: string };
A Post must carry every property of every part: name, createdAt, and body. This is the type-alias counterpart of extends, and real codebases use it to bolt shared fields — ids, timestamps, audit info — onto many shapes without repeating them. One caution: if two parts declare the same property with incompatible types, no value can satisfy both, so the property becomes impossible to construct. Keep the parts disjoint.
Quiz
Given type A = { x: number } and type B = { y: string }, what must a value of type A & B contain?