Implementing Interfaces in Classes
In this page:
Basic Interface Implementation
The implements keyword connects a class to an interface, and the compiler requires the class to provide every property and method the interface declares, or it will not compile.
Example: Basic Interface Implementation
interface Printable {
print(): void;
}
class Report implements Printable {
print() { console.log("Printing report"); }
}
new Report().print();
Interface Properties
An interface can describe properties that implementing classes must contain, giving TypeScript a structural contract to check the class against even though interfaces themselves produce no runtime code.
Example: Interface Properties
interface Vehicle {
wheels: number;
}
class Car implements Vehicle {
wheels: number = 4;
}
console.log(new Car().wheels);
Interface Methods
Interfaces can define method signatures that implementing classes must provide, specifying the parameter and return types without dictating how the method's body is actually written.
Example: Interface Methods
interface Calculator {
add(a: number, b: number): number;
}
class BasicCalculator implements Calculator {
add(a: number, b: number): number {
return a + b;
}
}
console.log(new BasicCalculator().add(2, 3));
Implementing Multiple Interfaces
A class can implement more than one interface at once, letting it satisfy several independent contracts simultaneously — useful when a class needs to be treated as, say, both Comparable and Serializable.
Example: Implementing Multiple Interfaces
interface Comparable {
compareTo(other: number): number;
}
interface Serializable {
serialize(): string;
}
class Score implements Comparable, Serializable {
constructor(public value: number) {}
compareTo(other: number) { return this.value - other; }
serialize() { return String(this.value); }
}
const s = new Score(90);
console.log(s.compareTo(80), s.serialize());
Why Implement Interfaces
Interfaces make class contracts explicit and let different, unrelated classes follow the same structural shape, which is what allows generic code to work with any of them interchangeably.
Example: Why Implement Interfaces
interface Shape {
area(): number;
}
class Square implements Shape {
constructor(public side: number) {}
area() { return this.side ** 2; }
}
class Circle implements Shape {
constructor(public radius: number) {}
area() { return 3.14 * this.radius ** 2; }
}
function printArea(shape: Shape) {
console.log(shape.area());
}
printArea(new Square(3));
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: