override / Method Overriding
| Since: | TypeScript 4.0(2020) |
|---|
The override keyword explicitly marks a method in a subclass as overriding a method from the parent class. If you accidentally apply override to a method that does not exist in the parent class, or if the parent class method is later removed, TypeScript will catch the mismatch at compile time.
Syntax
class Parent {
greet(): string { return 'Hello'; }
}
class Child extends Parent {
override greet(): string { return 'Hi'; }
}
Related Options
| Setting | Description |
|---|---|
| override keyword | Explicitly marks a method as overriding a parent class method. Requires TypeScript 4.3+. |
| noImplicitOverride | When enabled in tsconfig, all overriding methods must use the override keyword explicitly. |
| super.method() | Calls the original method from the parent class. |
Sample Code
class BaseWorker {
name: string;
constructor(name: string) {
this.name = name;
}
work(): string {
return `${this.name} is running a standard task.`;
}
toString(): string {
return `BaseWorker(${this.name})`;
}
}
class SeniorWorker extends BaseWorker {
// override makes it clear that work() exists in the parent class
override work(): string {
return `${this.name} is running a priority task!`;
}
override toString(): string {
return `SeniorWorker(${super.toString()})`;
}
}
const worker = new SeniorWorker('worker_1');
console.log(worker.work()); // worker_1 is running a priority task!
console.log(worker.toString()); // SeniorWorker(BaseWorker(worker_1))
// When noImplicitOverride is enabled
class JuniorWorker extends BaseWorker {
// Overriding without override causes an error
// work(): string { return 'working'; } // Error
override work(): string { return `${this.name} is running a sub-task!`; }
}
Running the above produces the following output:
npx ts-node ts_override.ts worker_1 is running a priority task! SeniorWorker(BaseWorker(worker_1))
Overview
In JavaScript (and traditional TypeScript code), defining a method with the same name in a subclass automatically overrides the parent class method. However, if the parent class method is renamed or removed, the subclass method silently becomes a new method instead — which is rarely the intended behavior.
Using the override keyword lets TypeScript detect this problem at compile time. By setting noImplicitOverride: true in tsconfig.json, you require that all overriding methods explicitly use override, improving safety in team development.
To call the original parent class method, use super.methodName(). This works similarly to super(), which calls the parent class constructor.
If you find any errors or copyright issues, please contact us.