Overload functions to change signatures and provide optional arguments in Typescript.
We have previously seen an option to provide optional arguments to a function in Typescript. But, there is more to that to function overloads.
Building on our previous example -
function getSum(i: number, j?: number, k?: number): number {
j = j || 0;
k = k || 0;
return i + j + k;
}
console.log(getSum(1));
// 1
In the example, we have simply made j and k optional arguments and made their value 0 if they are not provided. Although this is evident for someone who looks at the function definition, it is not so for a person looking at the declaration or the auto-complete when initializing this function.
Typescript provides a way to define function overloading during declaration so that we can make full use of the beautiful self-documenting feature.
Consider the same problem in the previous example written in a different way -
function getSum(i: number);
function getSum(i: number, j: number);
function getSum(i: number, j: number, k: number);
function getSum(i: number, j?: number, k?: number) {
j = j || 0;
k = k || 0;
return i + j + k;
}
console.log(getSum(1)); // 1
console.log(getSum(1, 2)); // 3
console.log(getSum(1, 2, 3)); // 6
While the last function is the one that actually gets executed, the developer who consumes this function sees a function with 3 options - provide i alone, i & j, or all of i,j & k.
Function overloading does not cause any runtime overhead, but it is invaluable to further the self-documenting goals of your project.