On this page

Implementing Interfaces in TypeScript: Contracts, Polymorphism & DI

Updated on July 27, 2026

Enrico Hochkoeppler Profile

By Enrico Hochkoeppler

Web Developer & TutoriaLibre Founder

When a class declares that it implements an interface using the implements keyword, it enters into a contract with the TypeScript compiler. The class promises to provide concrete implementations for every property and method that the interface defines. If the class fails to fulfil any part of this contract — by omitting a required member, using the wrong type, or mismatching method signatures — TypeScript raises a compile‑time error. This mechanism is not about inheritance; it is about enforcing structure and guaranteeing that a class meets the expectations of the interfaces it claims to support.


The implements Keyword: Basic Usage​

The syntax is straightforward: after the class name and any base class, add the implements keyword followed by the interface name. The class must then implement all members declared in the interface.


interface Logger {

  log(message: string): void;

}



class ConsoleLogger implements Logger {

  log(message: string): void {

    console.log(`[LOG] ${message}`);

  }

}

The ConsoleLogger class fulfils the Logger contract. If it omitted the log method, TypeScript would report an error:


class BadLogger implements Logger {

  // ❌ Error: Property 'log' is missing in type 'BadLogger'

  // but required in type 'Logger'.

}

The implements clause is purely a compile‑time construct. It does not affect the JavaScript output, nor does it create any runtime relationship between the class and the interface. Its sole purpose is to help the type checker verify that your classes correctly follow their contracts.


Implementing Multiple Interfaces​

A class can implement multiple interfaces by listing them after the implements keyword, separated by commas. This is one of the key advantages of interfaces over class inheritance — a class can only extend one base class, but it can implement any number of interfaces.


interface Shape {

  calculateArea(): number;

}



interface Color {

  color: string;

}



class Circle implements Shape, Color {

  radius: number;

  color: string;



  constructor(radius: number, color: string) {

    this.radius = radius;

    this.color = color;

  }



  calculateArea(): number {

    return Math.PI * this.radius * this.radius;

  }

}



const circle = new Circle(5, "red");

console.log(`Color: ${circle.color}`); // Color: red

console.log(`Area: ${circle.calculateArea()}`); // Area: 78.5398...

When implementing multiple interfaces, the class must satisfy all of them simultaneously. If two interfaces declare a member with the same name but incompatible types, the class cannot implement both.


Optional and Readonly Members​

Interfaces can include optional members (marked with ?) and readonly properties (readonly). When a class implements such an interface, it must respect these modifiers.


interface Config {

  readonly version: string;

  debug?: boolean;

}



class AppConfig implements Config {

  readonly version: string;



  constructor(

    version: string,

    public debug?: boolean,

  ) {

    this.version = version;

  }

}



const config = new AppConfig("1.0.0", true);

config.version = "2.0.0"; // ❌ Error: Cannot assign to 'version' because it is a read-only property.

The readonly modifier is enforced by the type checker. Optional properties may be omitted, but if they are present, their types must match.


Structural Typing: The TypeScript Distinction​

TypeScript uses structural typing, sometimes called "duck typing". A type is compatible with an interface based on its shape — the members it has — not based on its name or explicit declaration. This means that a class does not need to explicitly use the implements keyword to be compatible with an interface. If it has the required members, it automatically satisfies the contract.


interface Point {

  x: number;

  y: number;

}



class Coordinate {

  constructor(

    public x: number,

    public y: number,

  ) {}

}



const p: Point = new Coordinate(10, 20); // ✅ Allowed — same shape

In a nominally‑typed language like Java or C#, this would be an error unless Coordinate explicitly declared that it implements Point. In TypeScript, it is perfectly valid because the shape matches.

If the implements keyword is optional, why use it? The implements clause provides localised error checking. By adding it to the class declaration, you get immediate feedback at the class definition site if the contract is violated, rather than discovering the issue later when you try to use the class.


interface Shape {

  area: number;

}



class Rectangle implements Shape {

  // ❌ Error: Property 'area' is missing in type 'Rectangle'

  // but required in type 'Shape'.

  constructor(

    public width: number,

    public height: number,

  ) {}

}

Without implements, this error might only surface when a Rectangle is passed to a function expecting a Shape. The implements keyword moves the error closer to its source.


Polymorphism Through Interfaces​

Interfaces enable polymorphism — the ability to treat different objects uniformly through a common interface. This is a fundamental pattern in object‑oriented design.


interface PaymentProcessor {

  pay(amount: number): void;

}



class StripeProcessor implements PaymentProcessor {

  pay(amount: number): void {

    console.log(`Stripe: charged $${amount}`);

  }

}



class PayPalProcessor implements PaymentProcessor {

  pay(amount: number): void {

    console.log(`PayPal: charged $${amount}`);

  }

}



function checkout(processor: PaymentProcessor): void {

  processor.pay(50);

}



checkout(new StripeProcessor()); // Stripe: charged $50

checkout(new PayPalProcessor()); // PayPal: charged $50

The checkout function works with any object that satisfies the PaymentProcessor interface — regardless of the concrete class. This pattern is used throughout real‑world applications for logging, storage, payment gateways, messaging systems, and adapters.


Dependency Injection with Interfaces​

Interfaces make dependency injection straightforward. A class can declare its dependencies using interface types, allowing different implementations to be supplied at runtime.


interface StorageEngine {

  save(key: string, value: string): void;

  load(key: string): string | null;

}



class App {

  constructor(private storage: StorageEngine) {}



  start(): void {

    this.storage.save("status", "running");

    console.log(this.storage.load("status"));

  }

}



class MemoryStorage implements StorageEngine {

  private store = new Map<string, string>();



  save(key: string, value: string): void {

    this.store.set(key, value);

  }



  load(key: string): string | null {

    return this.store.get(key) ?? null;

  }

}



const app = new App(new MemoryStorage());

app.start(); // running

You can swap implementations without changing the App class — replace MemoryStorage with FileStorage, DatabaseStorage, or a mock for testing. This is how real‑world TypeScript applications achieve modularity and testability.


Putting It All Together​


interface Identified {

  id: string;

}



interface Timestamped {

  createdAt: Date;

  updatedAt: Date;

}



interface User extends Identified, Timestamped {

  name: string;

  email: string;

}



class PremiumUser implements User {

  id: string;

  name: string;

  email: string;

  createdAt: Date;

  updatedAt: Date;

  premiumUntil: Date;



  constructor(id: string, name: string, email: string) {

    this.id = id;

    this.name = name;

    this.email = email;

    this.createdAt = new Date();

    this.updatedAt = new Date();

    this.premiumUntil = new Date();

  }

}



function printUserInfo(user: User): void {

  console.log(`User: ${user.name} (${user.email}), since ${user.createdAt}`);

}



const user = new PremiumUser("1", "Alice", "[email protected]");

printUserInfo(user); // Works because PremiumUser satisfies the User interface

Summary​

Found this helpful? Share the knowledge...

... or support this project to keep it alive!

Buy Me a Coffee

Previous

Classes

Next

Hands‑On: Build a Typed Plugin System Using Interfaces