I have map
function:
const map = <T, U>(f: (x: T) => U, arr: T[]): U[] => {
return arr.map((val) => f(val));
}
When I'm calling map
with anonymous function as a callback, it's return type is correct:
// `x1` variable type here is { name: string }[], which is correct
const x1 = map(x => x, [{name: 'John'}]);
But when I'm providing identity
function instead of anonymous one, return type is wrong:
const identity = <T>(x: T) => x
// return type of `x2` is {}[] here
const x2 = map(identity, [{name: 'John'}]);
How to get correct type result for 2nd example, without providing explicit type arguments for map
function?
After some trying, I honestly doubt TypeScript is able to follow you that far. For example:
const x4 = map(identity, [2]);
// x4 is '{}[]'
which is obviosly even more wrong 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 lets me conclude that TypeScript just can't break all that generics down to a meaningful type and just says {}.
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