Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inconsistent typing [...].map() for point free or with an arrow function

Tags:

typescript

See this example:

const strings = ['1', '2', 2];
const mapper = (s: string) => parseInt(s, 10);
const numbers1 = strings.map(mapper);
const numbers2 = strings.map(s => mapper(s));

With this example, the line with numbers1 typechecks fine, which it shouldn't because strings has the type of (string | number)[], and mapper only accepts string arguments.

However if I use a lambda at numbers2 I do get the expected error as s is of type (string | number) that can't be passed into mapper.

Is there a reason for this, or is there maybe some 'strict' configuration to get the expected error, or is it simply a bug?

To run the example see: playground link

like image 348
arian Avatar asked Dec 12 '25 14:12

arian


1 Answers

There are similar issues / proposal on TypeScript github (for example: https://github.com/Microsoft/TypeScript/issues/1394).

Currently you have (s: string) => any implicitly cast to (s: string | number) => any. And TypeScript compiler for any generic argument think that it can be cast to "more wide" type (covariance). But for function parameters opposite thing should work (contravariance). And currently TypeScript doesn't support it.

like image 148
oryol Avatar answered Dec 15 '25 08:12

oryol