Sub topic 16
Abstract Classes and Abstract Members
This chapter assumes you know basic class syntax, extends and super, and the public, private and protected modifiers from earlier chapters. It covers how abstract classes define a contract plus shared behavior, the compiler rules around them, and the traps that appear at runtime.
What an abstract class is
An abstract class is a class that exists only to be extended. You mark it with the abstract keyword, and the compiler refuses to let you create instances of it directly. It can contain ordinary fields and methods with real implementations. It can also contain abstract members, which have a signature but no body. Every concrete subclass must implement those members.
abstract class Shape {
abstract area(): number;
describe(): string {
return `Area: ${this.area().toFixed(2)}`;
}
}
class Circle extends Shape {
constructor(private radius: number) {
super();
}
area(): number {
return Math.PI * this.radius ** 2;
}
}
console.log(new Circle(2).describe()); // Area: 12.57
// new Shape(); // Error: Cannot create an instance of an abstract class.describe is written once in Shape and calls area, which each subclass supplies. The base class can rely on a method it does not implement.
Rules the compiler enforces
| Situation | Compiler message (abridged) |
|---|---|
| `new Shape()` on an abstract class | Cannot create an instance of an abstract class |
| A subclass omits an abstract member | Non-abstract class does not implement inherited abstract member |
| `abstract` method in a non-abstract class | Abstract methods can only appear within an abstract class |
| Abstract method with a body | Method cannot have an implementation because it is marked abstract |
| `private abstract` | 'private' modifier cannot be used with 'abstract' modifier |
The last rule follows from how privacy works. A private member is invisible to subclasses, so a subclass could never implement it. Abstract members must be public or protected.
A subclass that does not implement every abstract member must itself be declared abstract. This lets you build a chain: a general abstract base, a more specific abstract class that fills in some members, and concrete classes at the bottom.
Abstract members beyond methods
Properties and accessors can also be abstract. A subclass may satisfy an abstract property with a field or with a getter.
abstract class Logger {
abstract readonly prefix: string;
log(message: string): void {
console.log(`${this.prefix} ${message}`);
}
}
class AppLogger extends Logger {
readonly prefix = "[app]";
}
new AppLogger().log("started"); // [app] startedThe template method pattern
Abstract classes are a natural fit for the template method pattern. The base class fixes the order of the steps, and subclasses fill in some of them. Using protected abstract keeps the steps out of the public API.
abstract class Report {
generate(): string {
return [this.header(), this.body(), this.footer()].join("\n");
}
protected abstract header(): string;
protected abstract body(): string;
protected footer(): string {
return "-- end --";
}
}
class SalesReport extends Report {
constructor(private total: number) {
super();
}
protected header(): string {
return "Sales";
}
protected body(): string {
return `Total: ${this.total}`;
}
}
console.log(new SalesReport(250).generate());
// Sales
// Total: 250
// -- end --Callers see only generate. The three step methods are protected, so they are available to subclasses and hidden from everyone else.
Abstract classes versus interfaces
Both describe a contract, but they differ in what they carry.
| Row | Abstract class | Interface |
|---|---|---|
| Exists at runtime | Yes, as a JavaScript class | No, erased |
| Shared implementation | Yes | No |
| Instance state and constructors | Yes | No |
| Access modifiers | Yes | Public members only |
| `instanceof` check | Works | Not possible |
| Number a class can use | One `extends` | Many `implements` |
Choose an abstract class when subclasses share code or state, or when you need instanceof. Choose an interface when you only need a shape, or when a class must satisfy several contracts. They combine well: an abstract class can implements an interface and leave some of its methods abstract.
Gotchas
Abstract is compile-time only
The abstract keyword is erased during compilation. The emitted JavaScript is an ordinary class, and abstract members produce no code. Nothing at runtime stops new Shape() if type checking is bypassed, for example by a cast to any or by plain JavaScript callers. If a hard runtime guarantee matters, check new.target in the constructor and throw.
Calling abstract members from the base constructor
The base constructor runs before the subclass's field initializers. An abstract method called from the base constructor can therefore see uninitialized state, and the compiler does not warn you.
abstract class Base {
constructor() {
console.log(this.name());
}
abstract name(): string;
}
class Derived extends Base {
private label = "derived";
name(): string {
return this.label;
}
}
new Derived(); // undefined, because label is assigned after Base's constructor finishesAvoid calling abstract members from a constructor. Put that work in a separate init() method that callers invoke after construction, or in a factory function.
Abstract classes as values
A parameter typed new () => Shape does not accept an abstract class, because it could not be instantiated. To accept constructors that might be abstract, for example to inspect the class, use an abstract construct signature (TypeScript 4.2 or later).
abstract class Shape {
abstract area(): number;
}
class Unit extends Shape {
area(): number {
return 1;
}
}
function build(ctor: new () => Shape): Shape {
return new ctor();
}
function nameOf(ctor: abstract new () => Shape): string {
return ctor.name;
}
console.log(build(Unit).area()); // 1
console.log(nameOf(Shape)); // Shape
// build(Shape); // Error: Cannot assign an abstract constructor type to a non-abstract constructor type.Abstract does not mean uninstantiable at the type level
You can still use an abstract class as a type. A variable typed Shape can hold any concrete subclass instance, so const shapes: Shape[] = [new Circle(1), new Unit()] works, and each element's area() dispatches to its own implementation.
Exercise
Given abstract class Animal { abstract sound(): string; speak(): string { return this.sound(); } }, what happens with class Dog extends Animal {} and with new Animal()? How do you fix each?
Show answer
Both are compile errors. Dog does not implement the inherited abstract member sound. Fix it by adding sound(): string { return "Woof"; } to Dog, or by declaring Dog as abstract. new Animal() is an error because abstract classes cannot be instantiated. Fix it by instantiating a concrete subclass such as new Dog() after Dog implements sound.
Exercise
A base class constructor calls this.describe(), which is abstract, and the subclass implementation reads a field initialized with private unit = "cm". What does the method see, and what is a safer design?
Show answer
The method sees undefined for unit, because the base constructor runs before the subclass's field initializers. A safer design removes the abstract call from the constructor. Use a separate method that callers invoke after construction, or a static factory function that constructs the object and then calls the method.