Implementing Interfaces with Classes
What you'll learn: How classes use the implements keyword to promise they'll match an interface's structure at compile time.
The Core Idea
An interface defines a contract — a shape that describes what properties and methods something should have. When a class implements an interface, it's making a promise: "I guarantee I'll have everything this interface requires."
TypeScript checks this promise at compile time. If your class is missing a property, misspells a method name, or uses the wrong type, you'll get an error before your code ever runs.
Think of it like a building inspector checking blueprints. The interface is the blueprint, the class is the actual building, and TypeScript is the inspector making sure everything matches before construction is approved.
Basic Syntax
interface Movable {
speed: number;
move(): void;
}
class Car implements Movable {
speed: number;
constructor(speed: number) {
this.speed = speed;
}
move(): void {
console.log(`Moving at ${this.speed} mph`);
}
}
const myCar = new Car(60);
myCar.move(); // Valid: Car fulfills the Movable contract
If you forget a required property or method:
class Bicycle implements Movable {
speed: number = 15;
// Error: Class 'Bicycle' incorrectly implements interface 'Movable'.
// Property 'move' is missing.
}
Why This Matters
The implements keyword doesn't change runtime behavior — it's purely a compile-time safety net. It catches mistakes early and documents your class's intended capabilities for other developers (and your future self).
Key Takeaway: Classes use implements to enforce that they match an interface's shape, giving you compile-time safety without affecting runtime behavior.