Better Programming

Advice for programmers.

Follow publication

Member-only story

Mastering Function Overloading in TypeScript

Jose Granja
Better Programming
Published in
6 min readJul 6, 2021

Code
Photo by Christopher Robin Ebbinghaus on Unsplash.

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…

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Jose Granja
Jose Granja

Written by Jose Granja

Top Writer @Medium | 1M+ Views | Lead FE @Lingoda | I write weekly about web-development topics 📰 Support me at https://dioxmio.medium.com/membership 🙇

Responses (4)

Write a response

More from Jose Granja and Better Programming