Skip to main content

Interfaces and Classes

While an interface natively designs standard Object logic layouts, it can remarkably also serve as an extremely rigid blueprint contract that a class is strictly forced to uphold securely.

We perform this using the implements keyword.

The implements Keyword

If a class maps the implements rule against an interface, the TypeScript compiler aggressively attacks the class if it misses any required parameters or matching method returns.

interface Drivable {
speed: number;
drive(): void;
honk(loudness: number): string;
}

// Car is legally forcing itself to match the 'Drivable' contract exactly!
class Car implements Drivable {
speed: number;

constructor(s: number) {
this.speed = s;
}

drive(): void {
console.log(`Driving at ${this.speed} mph`);
}

honk(loudness: number): string {
return `Honking at volume ${loudness}`;
}
}

// TS ERROR example:
// class Bicycle implements Drivable {}
// Error: Class 'Bicycle' incorrectly implements interface 'Drivable'.
// Property 'speed' is missing in type 'Bicycle' but required in type 'Drivable'.

Contract Independence

An important thing to understand is that the Interface solely ensures the public presence of properties and methods. It does not map logic functionality. The class still owns its core internal implementations natively.

A single class can also aggressively implement multiple distinct interfaces!

class HoverCar implements Drivable, Flyable {
// ... must implement both configurations!
}