TypeScript by Example

Class Contracts

Having classes implement interfaces and checking that required methods are present.

A class can implement one or more interfaces. TypeScript verifies that each required property and method exists with the right type.

implements checks the public shape of the class.

interface Serializable {
  serialize(): string;
  deserialize(data: string): void;
}
 
interface Validatable {
  validate(): boolean;
}
 
class Config implements Serializable, Validatable {
  private data: Record<string, string> = {};
 
  serialize(): string {
    return JSON.stringify(this.data);
  }
  deserialize(json: string): void {
    this.data = JSON.parse(json) as Record<string, string>;
  }
  validate(): boolean {
    return Object.keys(this.data).length > 0;
  }
}

In production

Use implements to catch drift where a class claims to satisfy an app-level contract. It checks the public surface only, so private fields and constructor details stay implementation details.

Enjoyed this? Get more software craft delivered to your inbox.