Typescript - Tips & Tricks - Overloaded Functions

Welcome back, guys! The topic of today is Overloaded Functions. All self-respecting programming...

#typescript #webdev
Luca Del Puppo Luca Del Puppo
Article Series · Part 5 of 21 TypeScript - Tips & Tricks
View full series (21)
  1. #4 Previous
    Union and Intersection
  2. #5 Reading now
    Overloaded Functions
  3. #6 Up next
    this parameter
Browse all 21 parts in this series
  1. #1 typeof
  2. #2 Literal Types
  3. #3 keyof
  4. #4 Union and Intersection
  5. #5 Overloaded Functions Current
  6. #6 this parameter
  7. #7 any vs. unknown
  8. #8 Optional modifier
  9. #9 Index Signature
  10. #10 readonly modifier
  11. #11 Readonly Array
  12. #12 Tuple
  13. #13 Non-null assertion operator
  14. #14 Never type
  15. #15 Assert Function
  16. #16 Type Guard
  17. #17 Conditional Type
  18. #18 infer keyword
  19. #19 Mapped Types
  20. #20 Advanced Types
  21. #21 Rest Parameters & Rest Arguments

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' ]

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!

Luca Del Puppo

Written by Luca Del Puppo

Run, Code & Learn

AI Native Engineer at Nearform based in Povegliano (TV), Italy. Google Developer Expert in Web Technologies, GitKraken Ambassador, and Codemotion Ambassador.