TS Interfaces
An interface is a named description of a shape — what properties and methods a value has. They're TypeScript's main contract type.
Declaring & implementing
TS
interface Payable {
total(): number;
description: string;
}
class Invoice implements Payable {
constructor(private amount: number, public description: string) {}
total() { return this.amount * 1.10; }
}
Extending interfaces
TS
interface Named { name: string }
interface Aged { age: number }
interface Person extends Named, Aged {
greet(): string;
}
Optional & readonly members
TS
interface Config {
readonly host: string;
port?: number;
log?: (msg: string) => void;
}
Function types
TS
interface Comparator<T> {
(a: T, b: T): number;
}
const byAge: Comparator<{ age: number }> = (a, b) => a.age - b.age;
Index signatures
TS
interface StringDict {
[key: string]: string;
}
Interface declaration merging
Interfaces with the same name in the same scope merge — handy for augmenting types from libraries:
TS
interface Window {
myAppVersion: string;
}
window.myAppVersion; // now typed (was missing before)
interface vs type
| Interface | Type alias |
|---|---|
extends with extends | extends with & |
| Declaration-merges | Doesn't merge |
| Slightly nicer error messages | More expressive (unions, conditionals) |
| Best for object shapes | Best for everything else (unions, primitives, mapped) |
Tip: Use
interface for "thing-shaped" types you might extend. Use type for unions, intersections, or conditional / mapped magic. Most projects mix both.Example
Example
interface Payable {
total(): number;
description: string;
}
class Invoice implements Payable {
constructor(private amount: number, public description: string) {}
total() { return this.amount * 1.10; }
}
const i = new Invoice(100, 'Hosting');
console.log(i.description, i.total());
Try it Yourself »
Exercise
Keyword that wires a class to an interface.
class Invoice
Payable {}
10 letters.
Discussion
Loading…