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
[Bug] Union type compilation failed in Array.map() #29850
// A *self-contained* demonstration of the problem follows...// Test this by running `tsc` on the command-line, rather than through another build tool such as Gulp, Webpack, etc.interfacefruit_t{name: stringcolor: string}interfaceresult_t{category: 'fruit'|'vegetable'|'animal'// If you change this union type into `string`, it will pass the compilation.name: string}constfruits: fruit_t[]=[{name: 'Apple',color: 'red'},{name: 'Banana',color: 'yellow'},{name: 'Citrus',color: 'orange'},]constresults: result_t[]=fruits.map(x=>({category: 'fruit',name: x.name}))console.log(results)
Expected behavior:
Has no error.
Actual behavior:
Type '{ category: string; name: string; }' is not assignable to type 'result_t'.
Types of property 'category' are incompatible.
Type 'string' is not assignable to type '"fruit" | "vegetable" | "animal"'.
17 const results: result_t[] = fruits.map(x => ({ category: 'fruit', name: x.name }))
~~~~~~~
It's not really a bug more of a design limitation. The arrow function is typed without any relation to the expected result, so there is no reason to keep the literal type 'fruit' it is widened to string. Then the map call is typed and the result is Array<{ category : string, name: string }> which is not assignable to results.
Beside the options mentioned by Aziz Khambati (@azizhk), I would also mention the syntax to specify the return type of an arrow function which would be the most succint in this case I believe.:
Activity
azizhk commentedon Feb 11, 2019
Maybe for a temporary workaround you can do
or
or
I would prefer using the 2nd and 3rd option as you don't use the
aswhich is almost equivalent to overriding Typescript type inference.dragomirtitian commentedon Feb 11, 2019
It's not really a bug more of a design limitation. The arrow function is typed without any relation to the expected result, so there is no reason to keep the literal type
'fruit'it is widened tostring. Then themapcall is typed and the result isArray<{ category : string, name: string }>which is not assignable toresults.Beside the options mentioned by Aziz Khambati (@azizhk), I would also mention the syntax to specify the return type of an arrow function which would be the most succint in this case I believe.:
ajafff commentedon Feb 11, 2019
In the upcoming typescript@3.4 you can use the following to prevent widening:
jack-williams commentedon Feb 11, 2019
This is fixed in 3.4 by #29478.
ahejlsberg commentedon Feb 11, 2019
Duplicate of #11152. As Jack Williams (@jack-williams) says above, this is fixed in 3.4 by #29478 (and no need for
as constin 3.4).