Closed
Description
TypeScript Version: 3.3.3
Search Terms:
Array.map, union type
Code
// 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.
interface fruit_t {
name: string
color: string
}
interface result_t {
category: 'fruit' | 'vegetable' | 'animal' // If you change this union type into `string`, it will pass the compilation.
name: string
}
const fruits: fruit_t[] = [
{ name: 'Apple', color: 'red' },
{ name: 'Banana', color: 'yellow' },
{ name: 'Citrus', color: 'orange' },
]
const results: 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 }))
~~~~~~~
Playground Link:
Related Issues: