Closed
Description
TypeScript Version: v3.5.1 (On TypeScript Playground)
Search Terms:
Arrow function overload
Code
const foo1 : {
(a: number): number;
(a: string): string;
} = (a: number | string): number | string => a;
// Type '(a: string | number) => string | number' is not assignable to type '{ (a: number): number; (a: string): string; }'.
// Type 'string | number' is not assignable to type 'number'.
// Type 'string' is not assignable to type 'number'.
const foo2 : {
(a: number): number;
(a: string): string;
} = (a: number | string): number & string => a as any;
function foo3(a: number): number;
function foo3(a: string): string;
function foo3(a: number | string): number | string {
return a;
}
Expected behavior:
The return value of implementation of overloading arrow function should be number | string
which is allowed with function.
Actual behavior:
TypeScript expect the return value of implementation of overloading arrow function should be number & string
.
Playground Link:
Related Issues:
Metadata
Metadata
Assignees
Type
Projects
Milestone
Relationships
Development
No branches or pull requests
Activity
IllusionMH commentedon Sep 18, 2019
This is correct error.
If you check how you should use result of this function (result of the implementation, skip overloads for now because implementation has no knowledge of input->output types mapping) you would expect that implementation will support both of this cases without type errors.
this can be achieved only by a type that is assignable to
number
andstring
at the same time and this isnumber & string
.If you'll have function that has signature
(a: number | string) => number | string
e.g.then it won't work in case described above.
In case of
foo1
you can useBut users will see only 2 correct signatures.
joshuaavalon commentedon Sep 19, 2019
@IllusionMH My problem is the result is not consistent with
function
.For example,
It shows
The error is on the overload signature.
However, the error in arrow function overload is on the implementation signature. As a result, function can return
string | number
orstring & number
without error.If I use
any
, I will lose the type check on return type.IllusionMH commentedon Sep 19, 2019
It can't be consistent with functions with current syntax. Function overloads has special syntax and therefore can provide special handling of return types.
Your examples are regular function assignment and without special syntax are indistinguishable from incorrect implementations.
You don't want to allow second case.
To request similarity you should create proper feature request/proposal with convincing use cases, instead of using Bug report template.
never
in it #45264mp3por commentedon Jul 7, 2024
How is it possible that the "correct" function returns
string & number
at the same time ? Thetype C = A & B
in TS is used to tell the compiler that the variable of type C will be both A and B at the same time, correct ?