Implementing Interfaces
Make a class promise to satisfy an interface with implements.
Syntax
class Circle implements Shape { }A class can implement an interface, guaranteeing it has all the properties and methods that interface requires. If anything is missing, TypeScript reports an error.
This is a great way to enforce a contract across many different classes.
Example
Loading editorβ¦
Press Run to execute the code.
When to use it
- A file storage service and an S3 storage service both implement a StorageProvider interface, making them interchangeable.
- A class is verified at compile time to satisfy a Serializable interface before being passed to a persistence layer.
- Multiple payment gateway classes implement a PaymentProcessor interface so the checkout can use any of them.
More examples
Class implements interface
Implements a Greeter interface on a class, enforcing that the greet method is present with the correct signature.
interface Greeter {
greet(name: string): string;
}
class FormalGreeter implements Greeter {
greet(name: string): string {
return `Good day, ${name}.`;
}
}
const g: Greeter = new FormalGreeter();
console.log(g.greet('Alice'));Implements multiple interfaces
Implements two separate interfaces at once, proving the class satisfies both contracts at compile time.
interface Identifiable { id: number; }
interface Serializable { serialize(): string; }
class Order implements Identifiable, Serializable {
constructor(public id: number, public item: string) {}
serialize(): string {
return JSON.stringify({ id: this.id, item: this.item });
}
}Interface as parameter type
Defines a StorageProvider interface, implements it, and uses the interface as the function parameter type for loose coupling.
interface StorageProvider {
save(key: string, value: string): void;
load(key: string): string | null;
}
class MemoryStorage implements StorageProvider {
private store: Record<string, string> = {};
save(key: string, value: string): void { this.store[key] = value; }
load(key: string): string | null { return this.store[key] ?? null; }
}
function cacheUser(storage: StorageProvider, name: string): void {
storage.save('user', name);
}
Discussion