π·
EPISODE 03
interface Β· extends Β· structural typing
Interface vs Type Alias
When to use interface and when to use type. Learn extends, declaration merging, and how structural typing decides assignability.
interfacetypeextendsstructural
Duration
β± About 1.5 hours
Level
π Intermediate
Prerequisite
π― ts-02
OUTCOME
Choose interface vs type consistently across a codebase
What you'll learn
- 1Define object shapes with interface
- 2Extend interfaces and intersect types
- 3Explain structural ("duck") typing
- 4Pick interface for libraries, type for everything else
1. interface
typescript
interface User {
id: number;
name: string;
email?: string;
greet(): string;
}
const alice: User = {
id: 1,
name: "Alice",
greet() { return `Hi, ${this.name}`; },
};2. Extending
typescript
interface Animal { name: string }
interface Dog extends Animal { bark(): void }
// Type alias intersection β equivalent
type DogT = Animal & { bark(): void };3. interface vs type β When
| Need | Pick |
|---|---|
| Object shape, especially for public API | interface |
| Union, tuple, primitive alias | type |
| Need declaration merging | interface |
| Computed / mapped types | type |
π‘
Many teams pick one consistently and stick with it. Either works for most cases.
4. Structural Typing
typescript
interface Point { x: number; y: number }
function print(p: Point) { console.log(p.x, p.y); }
print({ x: 1, y: 2, color: "red" }); // OK β extra props allowed at call site
// TS asks "does it have the right shape?" β not "is it nominally a Point?"Example code / lecture materials
All lecture materials and example code are openly available on GitHub.
View on GitHub β