DEV Community

Cover image for Typescript - Tips & Tricks - Overloaded Functions
Luca Del Puppo for This is Learning

Posted on • Edited on

3 1

Typescript - Tips & Tricks - Overloaded Functions

Welcome back, guys!
The topic of today is Overloaded Functions.

All self-respecting programming languages ​​have overloaded functions, so typescript has this feature too.
To use this feature in typescript, we have to declare all the signatures of this function, and at the end, we have to write a single function that includes all these signatures. The last function is the only one with the implementation. The peculiarity of this function is that it must include all the possible implementations of the previous signatures.
Here's a simple example that is more exhaustive than all these words.

function reverse(value: string): string;
function reverse(value: string[]): string[];
function reverse(value: string | string[]): string | string[] {
  if (typeof value === "string") return value.split("").reverse().join("");

  return value.slice().reverse();
}

console.log(reverse("Tips")); // 'spiT'
console.log(reverse(["T", "i", "p", "s"])); // [ 's', 'p', 'i', 'T' ]
Enter fullscreen mode Exit fullscreen mode

As we can see, there are 2 signatures of the "reverse" function, one gets a string and returns a string as result, the second one gets a string array and returns a string array as result. The third function is the real implementation of this function. As we can see the parameter type is a literal-type that includes a string or a string array (the combination of the type in the signatures' parameters), we can make the same considerations for the result's type.
In the function implementations, we detect the parameter's type at runtime and manipulate the parameter to return the correct type according to the function we are overloading.

An important thing to remember is that the implementation function is not exposed.

That's all for today!
See you soon guys!

Neon image

Build better on Postgres with AI-Assisted Development Practices

Compare top AI coding tools like Cursor and Windsurf with Neon's database integration. Generate synthetic data and manage databases with natural language.

Read more →

Top comments (1)

Collapse
 
jwp profile image
JWP

Thanks didn't know this one.

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay