We have an abstract
class Person
that contains a method display
and we wish to have our Employee
class extend Person
while ensuring that Employee
correctly overrides methods on the Person
class.
Approach
Using the override
keyword on the method display
will ensure that Person
has this method.
The benefit of this is that if in the future Person
is refactored changing display
to for example identify
then errors will be generated in subclasses that use the override keyword.
abstract class Person {
firstName: string;
lastName: string;
display(): string {
return `${this.firstName} ${this.lastName}`;
}
}
class Employee extends Person {
title: string;
override display() {
return `${this.title} ${this.firstName} ${this.lastName}`;
}
}
To make override
required when subclassing add this to tsconfig.json
.
{
"compilerOptions": {
// ...
"noImplicitOverride": true
}
}
Demo
Note that Stackblitz does not yet support the override
keyword, but hopefully this will be fixed soon.