I have this piece of code written in TypeScript with strict mode enabled.
const arr: ({ name?: string })[] = [
{ name: 'foo' },
{},
{ name: 'bar' }
]
function select(): string[] {
return arr
.filter(e => e.name !== undefined)
.map(e => e.name)
}
It fails to compile with this error:
Type '(string | undefined)[]' is not assignable to type 'string[]'.
Type 'string | undefined' is not assignable to type 'string'.
Type 'undefined' is not assignable to type 'string'.
Why is that? Aren't all objects with property name is undefined filtered out before being mapped? If I change the return type of the select function to (string | undefined)[], it compiles successfully.