Option 1: No type-check in the implementation, simply using any
You can make it type-check by adding types to the parameters of the implementation, such as adding : any
to the parameters in this case. This will still cause proper type-checking of any usage of the overloaded function, but will not have type-checking of the implementation, which may or may not be desirable. It might make the implementation of the overloaded function easier to write, but it may also make it more error-prone to implement, and callers from Javascript that do not use type-checking will not get any runtime errors if they call it with wrong arguments.
Playground Link
function plus(a: string, b: string): string;
function plus(a: number, b: number): number;
function plus(a: any, b: any): any {
return a + b;
}
console.log("Number: " + plus(3, 4));
console.log("String: " + plus("asdf", "qwer"));
// Does not compile.
//console.log("Mixed: " + plus(3, "testing"));
Option 2: Type-check in the implementation, here using string | number
for the parameters and return type
You can add more precise types to the parameters. In this case, it makes the overloaded function implementation more bothersome to implement, but it does enable type-checking of the implementation, and it also gives a runtime error if any callers from Javascript give wrong input to the overloaded function.
Playground Link
function plus(a: string, b: string): string;
function plus(a: number, b: number): number;
function plus(a: string | number, b: string | number): string | number {
if (typeof a === "string" && typeof b === "string") {
return a + b;
}
if (typeof a === "number" && typeof b === "number") {
return a + b;
}
throw new Error("Expected pair of strings or pair of numbers, but got: " + a + ", " + b);
}
console.log("Number: " + plus(3, 4));
console.log("String: " + plus("asdf", "qwer"));
// Does not compile.
//console.log("Mixed: " + plus(3, "testing"));
Side-notes.
Good catch that the official documentation does not compile either under ǹoImplicitAny
. I have created a pull request for fixing the example here: https://github.com/microsoft/TypeScript-Website/pull/652 .