Overloading the function signature

Method and function overloading is a common pattern in other languages such as C#. However, implementing this functionality in TypeScript clashes with the fact that JavaScript, which TypeScript is meant to compile to, does not implement any elegant way to integrate this functionality out of the box. So, the only workaround possibly requires writing function declarations for each of the overloads and then writing a general-purpose function that will wrap the actual implementation and whose list of typed arguments and returning types are compatible with all the others:

function hello(name: string): string {}
function hello(name: string[]): string {}
function hello(name: any, greeting?: string): string {
var namesArray: string[];
if (Array.isArray(names)) {
namesArray = names;
} else {
namesArray = [names];
}
if (!greeting) {
greeting = 'Hello';
}
return greeting + ', ' + namesArray.join(' and ') + '!';
}

In the preceding example, we are exposing three different function signatures and each of them feature different type annotations. We could even define different returning types if there was a case for that. For doing so, we should have just annotated the wrapping function with an any return type.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset