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
}
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.
TypeScript provides the concept of function overloading. You can have multiple functions with the same name but different parameter types and return type.
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.
Unlike the other programming languages, JavaScript Does not support Function Overloading.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With