Abstract classes and implementing interfaces
Checking a class against an interface with implements, sharing code through abstract classes, and how to choose between the two.
Abstract classes and implementing interfaces
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- `implements` asks the compiler to check that a class satisfies an interface; it doesn't change the class's type, add any members, or exist at runtime.
- Method parameters in a class that implements an interface are not typed from the interface, so they still need their own annotations under `noImplicitAny`.
- Because typing is structural, any object with the right shape satisfies an interface, whether or not a class declared `implements`.
- An abstract class can't be instantiated; it exists to be extended, and it can mix finished methods and state with `abstract` members that each subclass must provide.
- A subclass that leaves an abstract member unimplemented is a compile error, which turns the base class into a checklist.
- A plain constructor type `new () => T` rejects an abstract class; use `abstract new () => T` when a function only needs to refer to the class, not construct it.
- Reach for an interface when you only need a contract, and an abstract class when subclasses should also share code or state; a class can extend one class but implement many interfaces.
Two ways to say “these classes belong together”
Say you send notifications by email, SMS and push. Each sender is its own class, but the code that uses them shouldn’t care which it has. It just wants to call send. TypeScript gives you two tools for writing that shared expectation down. An interface describes the shape and nothing else. An abstract class describes the shape and can also hold code the senders share. They overlap enough to be confused, so it helps to see what each actually does.
implements is a check, not inheritance
You’ve already met interfaces. Adding implements to a class asks the compiler to verify the class against one:
interface Notifier {
channel: string;
send(to: string, message: string): Promise<void>;
}
class EmailNotifier implements Notifier {
channel = "email";
async send(to: string, message: string) {
console.log(`mail ${to}: ${message}`);
}
}
class SmsNotifier implements Notifier { // Error: Class 'SmsNotifier' incorrectly implements interface 'Notifier'.
channel = "sms";
}
That’s all it does. No members are copied in, the class’s own type is unchanged, and the clause is erased from the JavaScript. A common surprise follows from this:
class PushNotifier implements Notifier {
channel = "push";
async send(to, message) { // Error: Parameter 'to' implicitly has an 'any' type.
console.log(to, message);
}
}
const fake: Notifier = {
channel: "test",
send: async () => {},
};
The interface knows to is a string, but implements doesn’t pass that knowledge into the class. The class is typed first and checked afterwards, so its parameters need their own annotations.
The second half of that example matters too. fake never mentions Notifier in a class, yet it is one, because typing is structural. implements isn’t what makes a class a Notifier. It moves the error to the class declaration, where you can see it, instead of the first call site that passes a broken instance.
A class can implement several interfaces at once: class EmailNotifier implements Notifier, Disposable.
Abstract classes: a base you can’t instantiate
Now suppose every report your app produces has a title header, a format label, and a body that differs by format. The header logic is identical everywhere. An interface can’t hold it; an abstract class can:
abstract class Report {
constructor(protected readonly title: string) {}
abstract readonly format: string;
protected abstract renderBody(rows: string[]): string;
render(rows: string[]): string {
const header = `# ${this.title} (${this.format})`;
return `${header}\n${this.renderBody(rows)}`;
}
}
class CsvReport extends Report {
readonly format = "csv";
protected renderBody(rows: string[]) {
return rows.join("\n");
}
}
class HtmlReport extends Report { // Error: Non-abstract class 'HtmlReport' does not implement inherited abstract member renderBody from class 'Report'.
readonly format = "html";
}
new CsvReport("Sales").render(["a,1", "b,2"]);
new Report("Sales"); // Error: Cannot create an instance of an abstract class.
Think of a printed form with some fields already filled in and a few boxes marked “you must complete this.” The base class writes the finished parts, here the constructor and render, and declares abstract members for the blanks. The finished code can call the blanks, as render calls renderBody. Every concrete subclass must fill them in, and the compiler checks that it did.
Unlike an interface, an abstract class is real JavaScript. Report exists at runtime, CsvReport inherits from it through the normal prototype chain, and instanceof Report works. The abstract keyword itself is erased. It’s the compiler, not the engine, that refuses new Report(...).
Passing classes around
Abstractness shows up in constructor types too. A factory that calls new needs a class it can actually construct:
abstract class Report {
abstract render(): string;
}
class CsvReport extends Report {
render() {
return "a,b";
}
}
function build(ctor: new () => Report) {
return new ctor().render();
}
function describeKind(ctor: abstract new () => Report) {
return ctor.name;
}
build(CsvReport); // fine
build(Report); // Error: Argument of type 'typeof Report' is not assignable to parameter of type 'new () => Report'.
describeKind(Report); // fine: abstract construct signature
The abstract new form says “some class producing a Report, possibly abstract.” It’s what you want for registries, mixins, or anything that inspects a class without constructing it.
Choosing between them
Start with an interface. It costs nothing at runtime, any class or object literal can satisfy it, and a class can implement as many as it likes. Move to an abstract class when the implementations should share real code or state, like render above. The price is that JavaScript classes have single inheritance, so a class that extends Report can’t extend anything else.
The two combine well. An abstract class can itself implement an interface, so callers depend on the small contract while subclasses get the shared code.
About the video
Jack Herrington’s short video, part of his No BS TS series, is a compact, practical look at abstract classes and the subclasses that extend them. It spends less time on interfaces, so the implements section above and the comparison at the end carry that side of the lesson. His earlier episode on member visibility and implements is linked from the previous lesson, and the Hitesh Choudhary link below covers abstract classes with more contrast against interfaces.
Check yourself
A class declares `implements Notifier` but its `send` method has untyped parameters. Why does `strict` complain, when the interface already says what those parameters are?
`implements` is only a check performed after the class's own types are worked out; it doesn't feed the interface's parameter types into the class. Unannotated parameters are therefore implicitly `any`, which `noImplicitAny` reports. You have to annotate them in the class.
Can an object literal be used where a `Notifier` is expected if no class ever implemented `Notifier`?
Yes. TypeScript checks shapes, not declarations, so any value with a `channel` string and a matching `send` method is a `Notifier`. `implements` only moves the check to the class declaration, where mistakes are reported earlier and closer to their cause.
What does marking a method `abstract` give you that simply leaving it out of the base class would not?
It lets the base class call the method from its own finished code, such as a `render` method that calls `renderBody`, while forcing every concrete subclass to supply it. A subclass that forgets is a compile error rather than a runtime crash.
Why does `build(Report)` fail when `build` takes `ctor: new () => Report` and `Report` is abstract?
`new () => Report` promises the function can call `new ctor()`, and an abstract class can't be constructed. TypeScript reports that an abstract constructor type can't be assigned to a non-abstract one. If the function only needs the class itself, typing the parameter `abstract new () => Report` accepts it.
When would you choose an abstract class over an interface?
When the implementations should share real code or state, such as a common `render` method or a constructor that stores a title. An interface describes a shape and vanishes at compile time; an abstract class is a real JavaScript class that subclasses inherit from, but a class can only extend one of them.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.