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