Search code examples
typescriptoverloadingarrow-functions

typescript overload method with arrow function


anyone know how to use method overload on arrow function?

foo(args: string): string
    foo(args: number): number
    foo(args: string | number): string | number {
        if (typeof args === "string") {
            return "string"
        }
        return 1
    }

tried this but not working

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

Solution

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