Member-only story
Mastering Function Overloading in TypeScript
Use the overload feature to create more comprehensive and readable function types
If you have a background in any typed language, you are probably familiar with the concept of overloading. If not, let’s quickly recap what it is:
“In some programming languages, function overloading or method overloading is the ability to create multiple functions of the same name with different implementations. Calls to an overloaded function will run a specific implementation of that function appropriate to the context of the call, allowing one function call to perform different tasks depending on context.” — Wikipedia
It is a useful feature. Given that Javascript is not typed, is it posible to use implement it there? What are its caveats?
What about Typescript? Does it support overloading natively? Does it have any flaws?
In this article, we will be answering those questions. Once we have covered all the bases, we will see some best practices.
JavaScript Overloading
Is it possible to use overloading in JavaScript? Not from a strict point of view. We can manage to implement something that resembles overloading, but that approach has some flaws. Let’s investigate those with some examples.
Let’s say we want to create a concatString
function that can take 1-3 string parameters.
That looks OK. But what would happen if we invoke this method like this?
concatString('one', true);
The method would not crash but return an incorrect result. It is easy to fix. We can check the typeof
arguments to accept only strings.
if(s2 && typeof s2 === 'string')
So the problem with different types is “solved.” What about if we call the method with a different number of arguments? That’s another quick fix. We can check the arguments
length and return an…