Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
}
like image 224
Jemmy Phan Avatar asked Jun 08 '18 03:06

Jemmy Phan


People also ask

Can you use arrow functions in TypeScript?

ES6 version of TypeScript provides an arrow function which is the shorthand syntax for defining the anonymous function, i.e., for function expressions. It omits the function keyword. We can call it fat arrow (because -> is a thin arrow and => is a "fat" arrow). It is also called a Lambda function.

Can you overload a method in TypeScript?

TypeScript provides the concept of function overloading. You can have multiple functions with the same name but different parameter types and return type.

What is arrow in TypeScript?

Fat arrow notations are used for anonymous functions i.e for function expressions. They are also called lambda functions in other languages. Syntax: (param1, param2, ..., paramN) => expression.

Can you overload JavaScript functions?

Unlike the other programming languages, JavaScript Does not support Function Overloading.


1 Answers

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.

like image 171
a better oliver Avatar answered Sep 18 '22 15:09

a better oliver