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 -
|
|
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 -
|
|
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.