DEV Community

smac89
smac89

Posted on • Edited on

Overloading vs Overriding in Typescript

The main difference between overloading and overriding is this: The former is concerned with the signature of a function, whereas the later is concerned with the behaviour of a method.

Override

Override is something you do to change the behaviour of a method in a subclass. When you override a method, it is expected that you intend to change the default behaviour of the method, that was inherited from the parent class. However, the method signature should remain the same in order not to violate LSP.

Overload

Overload is something you do to functions; Not to change their behaviour*, but rather to diversify their signature. A function overload keeps the same name as the function, but it's free to introduce a different signature. You've probably seen an example of this if you come from a JavaScript background and seen functions which have parameters that can be one of two or more types:

/**
* @param {string|string[]} The object to use
*/
function stringOrArray(strOrArr) {
  ...
}
Enter fullscreen mode Exit fullscreen mode

It's difficult to tell that this is a function overload because JavaScript does not have a strong enough type system to disambiguate the overloads. However, with the Jsdoc comment, we can sort of make out that this function has an overload.
With typescript we can make this overload an actual part of our function signature, instead of living in a comment.

ex.

function stringOrArray(str: string)
function stringOrArray(arr: string[])
function stringOrArray(strOrArr: string | string[]) {
  ...
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

The implementation of the overloaded function stays the same, but the signature is allowed to be different. In the case of overriding, the implementation can be different, but the signature has to be the same, in order not to violate the Liskov Substitution Principle.

Top comments (0)