Skip to content

Przemysław Konieczniak - Dev Notes

Method overloading

TypeScript

Introduction

If you can delete the overload signatures and all of your tests pass, you don’t need TypeScript overloads

I found this statement in this article and it's hard to not agree with the author.

Whenever I reached the point that I felt a need to add overloading, then finally, I used other techniques to simplify the code.

Generally speaking, it's good to know that TS provides for us overloading but the usage of this technique should be minimalized.

Function overloading is used mostly in libraries or in packages. A good example of using this technique is Angular's source code (Angular-HttpClient). We can also meet overloading in type definitions files.

To overload a function in TypeScript:

  1. Create function signatures with different arguments. It's important to put the overloads in order from more specific to the most general.
  2. Provide the function definition that will fulfill the scenario for each signature.
1function pickCard(x: { suit: string; card: number; }[]): number;
2function pickCard(x: number): { suit: string; card: number; };
3function pickCard(x: any): any {
4 if (typeof x == "object") return Math.floor(Math.random() * x.length);
5 const pickedSuit = Math.floor(x / 13);
6 return { suit: suits[pickedSuit], card: x % 13 };
7}

As we can see overloading in TS is different than overloading in strongly typed languages like C# or Java.

The above-simplified example comes from the official TypeScript documentation and it's not too complicated, but with the increasing number of overloads, we would need to cover each case manually. In the end, we'll have a huge function with many conditions.

Resources

© 2020 by Przemysław Konieczniak - Dev Notes. All rights reserved.