When a method [on a child class] is marked with
override
, TypeScript will always make sure that a method with the same name exists in a the base class.
The override
keyword has been a long running feature of languages such as Java and C++, and since version 4.3, is now implemented in Typescript! 🎉
How Does it Work?
As the top quote explains, the override
keyword will assert that the function it describes is present in the parent class. This will help cut down on typos, and can give you a heads up if you were not aware that a function was changed/removed in the parent class.
abstract class Animal {
public sleep() {
// some default logic
}
public eat() {
// some default logic
}
}
class Unicorn extends Animal {
public override sleep() {
// some new logic
}
// Error! The method `eats` does not
// exist in the parent class!
public override eats() {
// some new logic
}
}
This is an example of implementing the wrong function due to a typo, and Typescript catching it for you before runtime!
If you'd like to make marking overridden methods with override
required, you can enable the noImplicitOverride
options in your tsconfig.json
.
{
"compilerOptions": {
// ...
"noImplicitOverride": true
}
}
Now, Typescript will throw an error if an overridden method does not include the override
keyword.
I hope you learned a bit about the override
keyword! If you have any questions, corrections, or addons, I would love to hear them. Peace ✌
Top comments (0)