typescript overload method with arrow function typescript overload method with arrow function typescript typescript

typescript overload method with arrow function


Arrow functions don't support overloading. From the language specification:

The descriptions of function declarations provided in chapter 6 apply to arrow functions as well, except that arrow functions do not support overloading.

When you write

foo: {  (args: string): string;  (args: number): number;}

then you don't overload. You actually say that foo is a function that can take one of these forms (or rather both forms). The arrow function

(args: string | number): string | number =>

violates that restriction because it's a single function (not an overloaded one) and string | number means that you can return a number when a string is expected.

As already proposed by artem changing the return type to any or an intersection type solves the problem. But it's not the same as overloading because the compiler doesn't chose between the signatures. You effectively only have one: That of the arrow function.


For reasons I don't fully understand, the return type of the implementation is expected to be intersection, not union:

class B {    foo: {        (args: string): string;        (args: number): number;    } = (args: string | number): string & number => {        if (typeof args === "string") {            return "string" as string & number;        }        return 1 as string & number;    }    }

So it's no better than just declaring the implementation to return any, as they do in documentation examples:

class B {    foo: {        (args: string): string;        (args: number): number;    } = (args: string | number): any => {        if (typeof args === "string") {            return "string";        }        return 1;    }    }