You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Array.map typechecking issues, doesn't typecheck what the .map callback returns #31425
TypeScript Version: reproducible in at least 3.3.3333 and above
Search Terms: Array map generic extra property
Code
typeToken={value: string}constthings=['one','two'];// using .map generic — doesn't fail typecheckingfunctiongetTokens1(){returnthings.map<Token>(thing=>({value: thing,// should say `somethingElse` does not exist on type `Token`somethingElse: true}));}// using return type — doesn't fail typecheckingfunctiongetTokens2(): Token[]{consttokens=things.map(thing=>({value: thing,// should say `somethingElse` does not exist on type `Token`somethingElse: true}));// type of tokens is reported as `{ value: string; somethingElse: boolean; }[]`// so how could it be compatible with `Token[]`?returntokens;}// following use cases as working proofs and potential workarounds// fails typechecking correctlyconsttoken: Token={value: 'one',somethingElse: true// `somethingElse` does not exist on type `Token`};// fails typechecking correctly — potential workaroundfunctiongetTokens3(){// note the `Token` inline return typereturnthings.map((thing): Token=>({value: thing,somethingElse: true// `somethingElse` does not exist on type `Token`}));}
Expected behavior:
I would expect in getTokens1 using the .map<U> generic form that it would typecheck what .map returns. Similarly, I would expect in getTokens2 that it would complain as I am precising the return type of the function and the inference itself seems to show an incompatible type.
Actual behavior:
It doesn't seem to typecheck properly when using Array.map.
I’m not sure why the first case isn’t an error (it seems like it should be, you’ve explicitly provided the result type for map and the object literal is still fresh when returned), but the second case is expected. See my comment here re: structural typing: #31412 (comment)
Activity
benoitgrelard commentedon May 16, 2019
https://medium.com/@lemoine.benoit/why-does-typescript-sometimes-fails-to-type-check-extra-properties-fd230ebbc295
Not a bug then?
fatcerberus commentedon May 16, 2019
I’m not sure why the first case isn’t an error (it seems like it should be, you’ve explicitly provided the result type for
mapand the object literal is still fresh when returned), but the second case is expected. See my comment here re: structural typing: #31412 (comment)Also see - https://github.com/basarat/typescript-book/blob/master/docs/types/freshness.md#freshness
RyanCavanaugh commentedon May 16, 2019
Duplicate #241
typescript-bot commentedon May 18, 2019
This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for house-keeping purposes.