Better Inheritance with the Typescript Override Keyword

Scenario

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 exampleidentify 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.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Ole Ersoy

Ole Ersoy

Founder of Firefly Semantics Corporation