Sub topic 11
Classes That Implement Interfaces
This chapter assumes you know basic TypeScript annotations, JavaScript classes, and object methods. You should also be able to run the TypeScript compiler or use an editor that reports type errors.
An interface describes the members an object must provide. A class can use implements to promise that its instances provide those members:
interface Logger {
log(message: string): void;
}
class ConsoleLogger implements Logger {
log(message: string): void {
console.log(message);
}
}
const logger: Logger = new ConsoleLogger();
logger.log("Application started");The implements Logger clause makes TypeScript check the ConsoleLogger class. If the class does not define a compatible log method, compilation fails.
What `implements` checks
implements checks the public instance side of a class. It checks property names, method parameters, and return types. It does not automatically generate any code.
interface UserStore {
findUser(id: number): string | undefined;
saveUser(name: string): void;
}
class MemoryUserStore implements UserStore {
private users = new Map<number, string>();
findUser(id: number): string | undefined {
return this.users.get(id);
}
saveUser(name: string): void {
this.users.set(this.users.size + 1, name);
}
}The class has an extra private users property. That is allowed because the interface describes the required public contract, not every implementation detail.
A missing member is an error:
interface PaymentGateway {
charge(cents: number): boolean;
}
class TestGateway implements PaymentGateway {
// Error: Property 'charge' is missing.
}A method with the wrong parameter or return type also fails the check:
class StrictGateway implements PaymentGateway {
charge(cents: string): boolean {
return cents.length > 0;
}
}The parameter must accept a number, because that is what the interface promises to callers.
Interfaces and class visibility
An interface member that a class implements must be accessible as a public member. A private or protected method cannot satisfy a public interface method.
interface Serializer {
serialize(value: object): string;
}
class JsonSerializer implements Serializer {
serialize(value: object): string {
return JSON.stringify(value);
}
}The constructor is not part of the instance interface in the usual implements check. To describe a class constructor, define a separate construct signature:
interface Service {
run(): void;
}
interface ServiceConstructor {
new (name: string): Service;
}
class ReportService implements Service {
constructor(private name: string) {}
run(): void {
console.log(`Running ${this.name}`);
}
}
function start(ServiceType: ServiceConstructor): Service {
return new ServiceType("daily report");
}
start(ReportService).run();A useful design pattern
Accept an interface in a function when the function needs behavior rather than a specific class:
function writeGreeting(logger: Logger): void {
logger.log("Hello");
}
writeGreeting(new ConsoleLogger());
writeGreeting({
log(message: string): void {
console.log(`[test] ${message}`);
},
});This keeps the function independent from ConsoleLogger. Any structurally compatible object can be used, which makes testing and replacement easier.
Common errors
- Implementing a property with the wrong type.
- Forgetting a required method.
- Making an implemented member private.
- Assuming
implementsvalidates constructor parameters. - Expecting interface checks to exist at runtime.
- Using a concrete class type where a smaller interface would express the real dependency.
Exercise
What must change in this class so it can implement interface Clock { now(): Date }?
class FakeClock implements Clock {
now(): string {
return "later";
}
}
Show answer
Change the return type to Date and return a Date value, such as return new Date(0).