Implicit type of output with function arguments in Typescript

I have a map function:

 const map = <T, U>(f: (x: T) => U, arr: T[]): U[] => { return arr.map((val) => f(val)); } 

When I call map with an anonymous function as a callback, the return type is correct:

 // `x1` variable type here is { name: string }[], which is correct const x1 = map(x => x, [{name: 'John'}]); 

But when I provide an identity function instead of an anonymous one, the return type is incorrect:

 const identity = <T>(x: T) => x // return type of `x2` is {}[] here const x2 = map(identity, [{name: 'John'}]); 

How to get the correct type result for the second example, without providing explicit type arguments for the map function?

+7
typescript
source share
1 answer

After some attempts, I honestly doubt that TypeScript is capable of following you that far. For example:

 const x4 = map(identity, [2]); // x4 is '{}[]' 

which is clearly more fallacious than your example.

Some other tests:

 const x2 = map(<({ name: string }) => { name: string }>identity, [{ name: 'John' }]); // x2 is '{ name: string }[]' 

and

 const double = (x: number) => 2 * x; const x3 = map(double, [2]); // x3 is 'number[]' 

This allows me to conclude that TypeScript simply cannot break all these generalizations into a meaningful type and simply says {}.

+2
source share

All Articles