Sub topic 17
Implementing interfaces with classes
This chapter assumes you know how to declare classes with typed fields and methods, and that you understand public, private, and protected. It also assumes you can write a basic interface. Here you will see how a class promises to match an interface, what the compiler checks, and where implements falls short of what people expect.
What `implements` does
An interface describes a set of members. A class that lists an interface after implements asks the compiler to verify that its instances have those members. The check happens at compile time only. TypeScript erases interfaces from the JavaScript output, so implements adds no runtime code and no instanceof support.
interface Logger {
readonly name: string;
log(message: string): void;
}
interface Closable {
close(): void;
}
class ConsoleLogger implements Logger, Closable {
constructor(public readonly name: string, private prefix: string = ">") {}
log(message: string): void {
console.log(`${this.prefix} [${this.name}] ${message}`);
}
close(): void {
console.log(`${this.name} closed`);
}
}
function run(logger: Logger): void {
logger.log("start");
}
const logger = new ConsoleLogger("app");
run(logger); // > [app] start
logger.close(); // app closedConsoleLogger implements two interfaces, separated by commas. It also has a private prefix that neither interface mentions. A class may have more members than its interfaces require.
What the compiler checks
The compiler compares the instance type of the class with each interface. If a required member is missing or has an incompatible type, the error appears on the class name.
interface Logger {
readonly name: string;
log(message: string): void;
}
class BrokenLogger implements Logger {
name = "broken";
// Error: Class 'BrokenLogger' incorrectly implements interface 'Logger'.
// Property 'log' is missing in type 'BrokenLogger' but required in type 'Logger'.
}Keep these points in mind:
- A class must implement every required member of the interface. Optional members (
log?(): void) may be left out. - A member that implements an interface member must be
public. Aprivateorprotectedmember cannot satisfy an interface requirement, because interfaces describe only the public side of a type. - A class that implements a
readonlyinterface property may declare it as writable. The compiler does not treatreadonlyas part of assignability. - Getters and setters can implement interface properties. An interface property
celsius: numbercan be satisfied by aget/setpair.
Common errors
The class does not inherit the interface's types
implements only checks. It does not copy member types into the class. A method parameter that you leave unannotated is not typed from the interface.
interface Handler {
handle(input: string): void;
}
class PrintHandler implements Handler {
// Error under noImplicitAny: Parameter 'input' implicitly has an 'any' type.
// handle(input) { console.log(input); }
handle(input: string): void {
console.log(input.toUpperCase());
}
}The same applies to optional members. If the interface declares timeout?: number and your class omits it, the class instance has no timeout property. Reading it through the class type is an error, even though reading it through the interface type is allowed.
`implements` is not required for compatibility
TypeScript uses structural typing. Any object with the right shape can be passed where Logger is expected, whether or not its class says implements Logger.
interface Logger {
readonly name: string;
log(message: string): void;
}
class SilentLogger {
name = "silent";
log(message: string): void {}
}
const l: Logger = new SilentLogger(); // OK: the shape matchesThe implements clause still earns its place. It makes the intent visible and moves the error to the class declaration. Without it, a missing method is reported later, at the place where you use the object.
Interfaces cannot enforce privacy
Because an interface lists only public members, you cannot require a private member through an interface. Parameters typed as Logger also cannot reach the prefix field of ConsoleLogger, even though the object has it.
Interfaces that extend classes
An interface can extend a class. It inherits the class's members, including private and protected ones, but supplies no implementations. The result is an interface that only the class itself or its subclasses can implement.
class Control {
private state = 0;
select(): void {
console.log(`state: ${this.state}`);
}
}
interface SelectableControl extends Control {
select(): void;
}
class Button extends Control implements SelectableControl {}
class Fake implements SelectableControl {
// Error: Class 'Fake' incorrectly implements interface 'SelectableControl'.
// Types have separate declarations of a private property 'state'.
select(): void {}
}
new Button().select(); // state: 0This is the structural-typing rule for private members in action. A private member ties the type to one specific declaration, so Fake cannot imitate it.
Choosing between `implements` and `extends`
| Need | Use |
|---|---|
| Share code between classes | `extends` (inheritance) |
| Guarantee a public contract with no shared code | `implements` |
| Require several unrelated contracts | `implements A, B` (a class can extend only one class) |
| Share a base with fixed members and required hooks | `abstract class` |
An interface suits a contract that unrelated classes meet in their own ways, such as a Logger with a console version and a file version. An abstract class suits a family of types that share state or default behavior.
Exercise
A class declares private log(message: string): void {} and lists implements Logger, where Logger requires log(message: string): void. Does it compile? Why or why not?
Show answer
No. An interface describes the public side of a class, so the class member that satisfies it must be public. The compiler reports that the class incorrectly implements Logger because log is private in the class but public in the interface.
Exercise
Given interface Handler { handle(input: string): void }, you write class H implements Handler { handle(input) {} } with noImplicitAny on. What error appears, and how do you fix it?
Show answer
The error is "Parameter 'input' implicitly has an 'any' type." The implements clause checks the class but does not give its methods contextual types. Fix it by annotating the parameter: handle(input: string): void {}.