Sub topic 15
Safe overriding with the override keyword
This chapter assumes you know how extends and super work, what protected means, and how to edit tsconfig.json. Here you will learn how the override modifier makes the compiler check your subclass methods against the base class.
The problem: silent overrides
In JavaScript and in plain TypeScript, a subclass method overrides a base method just because the names match. The compiler never asks whether you meant to override anything. That causes two bugs.
- Base rename. Someone renames a method in the base class. The subclass method keeps its old name, so it stops overriding anything. It is now an unrelated method, and nothing reports an error.
- Accidental override. You add a method to a subclass. The base class already has a method with that name, and you replace its behavior without noticing.
The first case looks like this:
class Logger {
write(message: string): void {
console.log(message);
}
info(message: string): void {
this.write(`INFO ${message}`);
}
}
class PrefixLogger extends Logger {
// Written when the base method was still called log().
// The base class was later renamed to write(), so this is now a new method.
log(message: string): void {
super.write(`[app] ${message}`);
}
}
new PrefixLogger().info("started"); // INFO started (no "[app]" prefix)The code compiles, runs, and drops the prefix.
The override modifier
Put override before a method that is meant to replace a base class member. The compiler then checks that the base class declares a member with that name.
class Logger {
write(message: string): void {
console.log(message);
}
info(message: string): void {
this.write(`INFO ${message}`);
}
}
class PrefixLogger extends Logger {
override write(message: string): void {
super.write(`[app] ${message}`);
}
}
new PrefixLogger().info("started"); // [app] INFO startedIf the base class has no write, the compiler reports an error such as "This member cannot have an 'override' modifier because it is not declared in the base class 'Logger'". The rename bug now fails at compile time. The error also appears if the containing class does not extend anything.
override is erased during compilation. It adds no runtime check and changes no emitted JavaScript.
Making it mandatory with noImplicitOverride
Writing override is optional by default, so the accidental-override bug can still happen. Turn on noImplicitOverride to close that gap:
{
"compilerOptions": {
"target": "ES2022",
"strict": true,
"noImplicitOverride": true
}
}With this option, any member that overrides a base class member must carry override. Otherwise the compiler reports "This member must have an 'override' modifier because it overrides a member in the base class". Now every override is deliberate. Reviewers can see the intent in the code, and a rename in the base class breaks every subclass that depends on the old name.
flowchart TDThe diagram below shows how the compiler decides what to report for a member in a subclass.
Where override can be used
override works on more than methods:
- Methods: the common case.
- Properties: a field redeclared in a subclass, for example to give it a new default.
- Accessors:
override getandoverride set. - Static members: the check runs against the base class constructor's static side.
- Parameter properties: the modifier goes in the constructor signature.
class Base {
constructor(public name: string) {}
get label(): string {
return this.name;
}
static create(): Base {
return new Base("base");
}
}
class Derived extends Base {
constructor(override name: string, private suffix: string) {
super(name);
}
override get label(): string {
return `${super.label}-${this.suffix}`;
}
static override create(): Derived {
return new Derived("derived", "x");
}
}
console.log(Derived.create().label); // derived-xWhen override appears with an accessibility modifier, the accessibility modifier comes first: protected override, public override. For a static member, the order is static override, as in the create method above. A constructor cannot be marked override, because every class has its own constructor.
Rules the override must still follow
override only confirms that the base member exists. The usual compatibility rules still apply.
- The subclass signature must be assignable to the base signature. A method that requires an extra parameter, or returns an incompatible type, is an error.
- An override may widen visibility, from
protectedtopublic. It may not narrow it, sopublictoprivateis an error. - A subclass cannot override a
privatebase member. The base member is not visible to the subclass, so the compiler reports a conflict between the declarations.
class Employee {
protected bonus(): number {
return 100;
}
}
class Intern extends Employee {
// Widening protected to public is allowed.
public override bonus(): number {
return 0;
}
}
console.log(new Intern().bonus()); // 0Abstract members and interfaces
Implementing an abstract method is not treated as an accidental override, so noImplicitOverride does not demand the modifier there. You may still write override on an implementation if you want the base-class check, and some teams do for consistency.
Implementing an interface with implements is a separate relationship. The override modifier only applies to members inherited through extends, so you cannot use it on a member that comes only from an interface.
Gotchas
- Redeclared fields. With
useDefineForClassFieldsenabled, which is the default when the target is ES2022 or later, a subclass field declaration such asoverride name = "x"is initialized after the base constructor runs. A base constructor that reads that field sees the base value, not the subclass value. - Generated or mixin code. When a base class comes from a library, an upgrade that adds a method with the same name as one of yours now produces an error under
noImplicitOverride. That error is useful, because it flags a change in behavior you might otherwise miss. - Declaration files.
overridechecks only what the base class type declares. If the base class is typed loosely, such asany, there is nothing to check against.
Summary of settings
| Setting | `override` on non-overriding member | Missing `override` on overriding member |
|---|---|---|
| Default (no flag) | Error | Allowed |
| `noImplicitOverride: true` | Error | Error |
Exercise
A base class Cache has a method clear(): void. A subclass LruCache defines clear(): void without override. The project has noImplicitOverride enabled. Later, a teammate renames Cache.clear to reset. Describe what the compiler reports at each step, and what you must change after the rename.
Show answer
Before the rename, the compiler reports an error on LruCache.clear, because it overrides a base member without the override modifier. Fix it by writing override clear(): void. After the teammate renames the base method to reset, the compiler reports an error on LruCache.clear, because override is used but clear is no longer declared in Cache. You then rename the subclass method to reset, keeping override, so the subclass behavior still applies. Without override, the old clear would have silently become an unrelated method.