Sub topic 11
Classes that implement interfaces
This chapter assumes you can write TypeScript classes with typed fields and methods, and that you know how interfaces describe object shapes. It covers what implements does, what it does not do, and the errors people hit most often.
What implements does
A class can declare that it implements an interface. The compiler then checks that every instance member the interface requires is present in the class with a compatible type.
interface Logger {
log(message: string): void;
}
class ConsoleLogger implements Logger {
log(message: string): void {
console.log(message);
}
}
const logger: Logger = new ConsoleLogger();
logger.log("started");The implements Logger clause is a check, not a source of members. If you delete the log method from ConsoleLogger, the error appears on the class declaration, which is a better place than a distant call site.
Because TypeScript uses structural typing, the assignment const logger: Logger = new ConsoleLogger() would compile even without implements. The class has a compatible log method, so it matches the shape. The clause documents your intent and moves the error to the class when the class drifts from the contract.
What implements does not do
An implements clause does not change the class's own type. It also does not give the class any inherited members. Two consequences follow.
Parameter types are not inferred
Method parameters in a class are not contextually typed from the interface. This surprises many people.
interface Formatter {
format(input: string): string;
}
class Shout implements Formatter {
// `input` has an implicit any here, so this errors under noImplicitAny
// format(input) { return input.toUpperCase(); }
format(input: string): string {
return input.toUpperCase();
}
}Write the parameter types yourself. This differs from assigning an arrow function to a variable of function type, where the parameter types are inferred.
Optional members are not added
If the interface declares an optional member, the class does not receive it.
interface Options {
name: string;
verbose?: boolean;
}
class Job implements Options {
name = "build";
}
const job = new Job();
// job.verbose; // error: Property 'verbose' does not exist on type 'Job'.The class satisfies Options, but Job itself has no verbose property. Declare the field in the class if you need it.
Implementing several interfaces
A class can implement a list of interfaces, separated by commas. It must satisfy all of them.
interface Readable {
read(): string;
}
interface Writable {
write(data: string): void;
}
class Buffer implements Readable, Writable {
private chunks: string[] = [];
write(data: string): void {
this.chunks.push(data);
}
read(): string {
return this.chunks.join("");
}
}
function copy(from: Readable, to: Writable): void {
to.write(from.read());
}
const a = new Buffer();
const b = new Buffer();
a.write("hello");
copy(a, b);
console.log(b.read()); // helloSplitting capabilities into small interfaces lets each function ask for only what it needs. copy accepts anything readable and anything writable, so it works with objects that have nothing else in common with Buffer.
This is the main design reason to use implements. A class extends at most one base class, but it can implement many interfaces.
Extending a class and implementing an interface together
A class can use extends for a base class and implements for contracts at the same time. The extends clause comes first.
interface Serializable {
serialize(): string;
}
class Entity {
constructor(public readonly id: number) {}
}
class Product extends Entity implements Serializable {
constructor(id: number, public name: string) {
super(id);
}
serialize(): string {
return JSON.stringify({ id: this.id, name: this.name });
}
}
console.log(new Product(1, "Lamp").serialize());The interface can also be satisfied by inherited members. If Entity already had a serialize method, Product would not need to define one.
Interfaces describe the public side only
An interface describes the public members of an instance. A class can implement an interface that has properties, but it cannot use private or protected for a member the interface declares.
interface Named {
name: string;
}
// class Bad implements Named {
// private name = "x";
// }
// error: Property 'name' is private in type 'Bad' but not in type 'Named'.
class Good implements Named {
name = "x";
}The class may have extra private members of its own, as Buffer did with chunks. The interface does not see them.
Static members and constructors are not covered either. The implements clause checks the instance side only. To describe a constructor, you need a separate construct signature:
interface Animal {
speak(): string;
}
interface AnimalConstructor {
new (name: string): Animal;
}
class Dog implements Animal {
constructor(private name: string) {}
speak(): string {
return `${this.name} says woof`;
}
}
function create(ctor: AnimalConstructor, name: string): Animal {
return new ctor(name);
}
console.log(create(Dog, "Rex").speak());The class Dog is passed as a value. The compiler checks its constructor against AnimalConstructor, and the instance against Animal.
Which types a class can implement
An interface is the usual target, but a class can also implement an object type alias, as long as the alias resolves to an object type with statically known members.
type Disposable = {
dispose(): void;
};
class Connection implements Disposable {
dispose(): void {
console.log("closed");
}
}Two limits apply. A class cannot implement a union type, because the class would have to be one of several shapes at once. A class also cannot implement a mapped type whose keys are not known at declaration time.
type Shape = { kind: "circle"; radius: number } | { kind: "square"; side: number };
// class Circle implements Shape {}
// error: A class can only implement an object type or intersection of object types
// with statically known members.An intersection of object types is allowed, since the result is a single object shape.
Implementing an interface with a method versus a property
An interface can declare a function-valued member as a method or as a property. A class can satisfy either with a method or an arrow-function field.
interface Handler {
handle(event: string): void;
}
class ArrowHandler implements Handler {
handle = (event: string): void => {
console.log(event);
};
}
class MethodHandler implements Handler {
handle(event: string): void {
console.log(event);
}
}Both compile. They behave differently at run time. The method lives on the prototype and is shared by all instances. The arrow-function field is created per instance and keeps this bound to that instance. Choose by how you will pass the function around, not by what the interface says.
Method parameter bivariance
TypeScript checks method parameters bivariantly when a member is declared with method syntax. A class method can therefore accept a narrower parameter type than the interface declares, and the compiler will allow it.
interface Visitor {
visit(node: string | number): void;
}
class StringVisitor implements Visitor {
visit(node: string): void {
console.log(node.toUpperCase());
}
}
const v: Visitor = new StringVisitor();
// v.visit(42); // compiles, then fails at run time: node.toUpperCase is not a functionThis is unsound. The strictFunctionTypes option tightens the check for properties declared with function-type syntax, but members declared with method syntax stay bivariant. If you want the strict check, declare the interface member as a property: visit: (node: string | number) => void;. The same StringVisitor class then fails to compile.
Interfaces are erased
Interfaces exist only at compile time. The emitted JavaScript contains the class but no trace of implements. You cannot test x instanceof Logger, because Logger is not a value.
interface Logger {
log(message: string): void;
}
function isLogger(x: unknown): x is Logger {
return typeof x === "object" && x !== null && typeof (x as Logger).log === "function";
}When you need a run-time check, write a type guard that tests for the members, as above. If you need instanceof, use an abstract class instead, which exists at run time and can still be implemented by other classes.
Common errors
| Error | Cause | Fix |
|---|---|---|
| Class incorrectly implements interface: property is missing | A required member is absent | Add the member to the class |
| Parameter implicitly has an `any` type | Parameters are not inferred from the interface | Annotate each parameter |
| Property is private in type but not in the interface | Interface members are public | Remove `private` or `protected` |
| Property does not exist on the class | An optional interface member was not declared in the class | Declare the field in the class |
| A class can only implement an object type | The target is a union or has dynamic keys | Implement an object shape instead |
Exercise
A class declares implements Options, where Options has name: string and verbose?: boolean. The class declares only name. Does new Job().verbose compile, and why?
Show answer
No. The implements clause only checks that the class is compatible with the interface. It does not copy members into the class, so Job has no verbose property and the compiler reports that the property does not exist on type Job. Declare verbose?: boolean in the class to read it.
Exercise
An interface declares visit(node: string | number): void;. A class implements it with visit(node: string): void. Why does this compile, and how do you make the compiler reject it?
Show answer
Members declared with method syntax are checked bivariantly, so a narrower parameter type is accepted. Declare the interface member as a function-typed property, visit: (node: string | number) => void;, so that strictFunctionTypes applies and the narrower class method is rejected.