Sub topic 13
Inheritance with extends and super
This chapter assumes you know TypeScript types and annotations, how this behaves in JavaScript methods, and the basic idea of object-oriented programming. It also assumes you have seen class fields, constructors, and parameter properties.
What extends does
extends creates a subclass (also called a derived class) from a base class. Each instance of the subclass gets the base class's members, and the subclass can add members or replace them. At runtime, extends links prototypes. Dog.prototype inherits from Animal.prototype, and the Dog constructor function inherits from the Animal constructor function, so static members are inherited too.
A class can extend only one class. To combine several sets of behavior, use interfaces or composition.
class Animal {
constructor(public readonly name: string) {
console.log("Animal constructor");
}
speak(): string {
return `${this.name} makes a sound`;
}
}
class Dog extends Animal {
constructor(name: string, private tricks: string[] = []) {
super(name);
console.log("Dog constructor");
}
speak(): string {
return `${super.speak()}: woof`;
}
addTrick(trick: string): void {
this.tricks.push(trick);
}
}
const dog = new Dog("Rex");
console.log(dog.speak()); // Rex makes a sound: woof
console.log(dog instanceof Animal); // trueThe output order is Animal constructor, then Dog constructor, then the two console.log results. The base constructor always finishes before the derived constructor continues.
The two uses of super
super means two different things depending on where you write it.
| Form | Where | Meaning |
|---|---|---|
| `super(args)` | Derived constructor | Calls the base constructor and creates `this` |
| `super.method(args)` | Any method | Calls the base class's version of a method |
In a derived class, this does not exist until super(...) returns. For that reason a derived constructor must call super(...), and it cannot touch this before doing so. TypeScript reports both mistakes:
- Missing call:
Constructors for derived classes must contain a 'super' call. - Early access:
'super' must be called before accessing 'this' in the constructor of a derived class.
If the subclass declares no constructor, TypeScript supplies one that forwards all arguments to the base constructor. You only write a constructor when the subclass needs extra state or a different signature.
Since TypeScript 4.6 you may run code before super(...), such as validating arguments, as long as that code does not reference this. Older versions required super(...) to be the first statement whenever the class had initialized fields or parameter properties.
super.method() works only for methods on the base prototype. It does not work for fields, because fields live on the instance and not on the prototype. Writing super.name for a field is a compile error: Only public and protected methods of the base class are accessible via the 'super' keyword.
Initialization order
The order in which state is set up matters whenever a base constructor calls an overridable method.
The base class initializes first. The derived class's own fields are assigned only after super(...) returns. This produces a well-known trap:
class Base {
constructor() {
console.log(this.describe());
}
describe(): string {
return "base";
}
}
class Derived extends Base {
private label = "derived";
describe(): string {
return `label=${this.label}`;
}
}
new Derived(); // label=undefinedThe base constructor calls the overridden describe, but label has not been assigned yet. TypeScript does not warn about this. Avoid calling overridable methods from a constructor, or make sure those methods do not depend on state the subclass sets up.
Overriding and type compatibility
A subclass method replaces the base method of the same name. The replacement must remain compatible with the base signature, because code holding a Base reference may be using a Derived object. A subclass method can accept the same or wider parameter types and return the same or narrower type. This compiles:
class Repository {
find(id: string): object | undefined {
return undefined;
}
}
class UserRepository extends Repository {
find(id: string): { id: string; name: string } | undefined {
return { id, name: "Ada" };
}
}
const repo: Repository = new UserRepository(); // OK: a subclass instance is a base type
console.log(repo.find("u-1")); // { id: 'u-1', name: 'Ada' }Changing the return type to something incompatible, such as number, is an error: Property 'find' in type 'X' is not assignable to the same property in base type 'Repository'. Section "Safe overriding with the override keyword" covers the override keyword, which catches typos in override names.
Subclass fields follow the same rule. You may narrow a field's type in a subclass, but you cannot make it incompatible with the base type.
Extending built-in classes
Extending Error is common, and it has one gotcha. When the compile target is ES5, built-in constructors return a new object and the prototype chain breaks. Then instanceof HttpError is false and subclass methods are missing. The fix is to reset the prototype with new.target:
class HttpError extends Error {
constructor(public readonly status: number, message: string) {
super(message);
this.name = "HttpError";
Object.setPrototypeOf(this, new.target.prototype);
}
isClientError(): boolean {
return this.status >= 400 && this.status < 500;
}
}
try {
throw new HttpError(404, "Not found");
} catch (e) {
if (e instanceof HttpError) {
console.log(e.name, e.status, e.isClientError()); // HttpError 404 true
}
}With an ES2015 or later target, the Object.setPrototypeOf line is harmless but unnecessary.
Common mistakes
- Forgetting
super(...). The compiler catches it. - Using
thisbeforesuper(...). The compiler catches it. - Calling overridable methods from a base constructor. The compiler does not catch it, and fields are still
undefinedat that point. - Deep hierarchies. Each level couples a subclass to its parent's internals. When a subclass only needs to use another class and does not have to be substitutable for it, hold an instance as a field instead.
- Redeclaring a base field without an initializer. Depending on the
useDefineForClassFieldssetting, which defaults to on for ES2022 and later targets, a barename: string;in a subclass can reset the inherited value toundefined. If you only want to narrow the type, usedeclare name: string;.
Exercise
A class Cat extends Animal declares private lives = 9; and overrides speak() to return a string containing this.lives. The Animal constructor calls this.speak(). What does the lives part of the string contain when you run new Cat("Tom"), and why?
Show answer
It is undefined. The Animal constructor runs before Cat's field initializers, so lives has not been assigned when the overridden speak() executes. The fix is to avoid calling speak() from the base constructor, or to make speak() not depend on Cat's fields.
Exercise
Why does super.name fail to compile when name is a field on the base class, and what is the correct way to read it in a subclass method?
Show answer
super.x looks up members on the base class prototype, and fields are stored on the instance, not the prototype. Inside the subclass, read the field with this.name, because the instance already holds the inherited value.