← Back to TypeScript Course | Chapter 6: Classes | Lesson 8 of 9

Implementing Interfaces in Classes

A class can implement an interface to promise that it provides specific properties and methods. This creates a clear contract between the class and the code that uses it.

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

typescript
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

typescript
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

typescript
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

typescript
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

typescript
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));

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.