Method overloading is a familiar concept from traditional programming languages like Java or C#. It allows a class to have multiple methods with the same name if their signature is different.

But Typescript only helps us during edit and compile time and not at runtime. Therefore method overloading works differently. The executed code is still pure Javascript.

Due to the dynamic nature of JavaScript, we can’t use overloading in the same way we do in other languages. Let’s have a look at JavaScript’s function parameter rules: ☝️

- JavaScript function definitions do not specify data types for parameters. - JavaScript functions do not perform type checking on the passed arguments. - JavaScript functions do not check the number of arguments received.

The third rule is especially interesting in the context of method overloading. Let’s have a closer look.

The code above is valid and doesn’t produce an error even if we pass more arguments than required or also if we don’t pass any arguments at all.

Missing parameters will result in undefined; additional parameters will be accessible in an “arguments” object.

Follow me on Twitter or medium to get notified about the newest blog posts and interesting frontend stuff!🐤

Of course, Typescript will complain in the scenarios above. But remember this is only during edit and compile time, not at runtime.

Illustrating the problem 🕵🏼

Let’s keep that in mind and have a look at a concrete example where we want to use overloading with typescript. Let’s imagine we have the following service:

and the corresponding component:

The Typescript compiler warns us about a bunch of things. Nevertheless, the application starts. So let’s inspect the code that is executed.

If the user enters a name and no skill, we would expect getHero(name: string) to be called. But guess what happens? We always enter our breakpoint in getHero(name: string, skill: string).