Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implicit type inferring with function arguments in Typescript

Tags:

typescript

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?

like image 247
1ven Avatar asked Jul 30 '17 17:07

1ven


1 Answers

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 {}.

like image 135
SVSchmidt Avatar answered Oct 12 '22 03:10

SVSchmidt