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 map
ped? If I change the return type of the select
function to (string | undefined)[]
, it compiles successfully.
You filtered an array but that filter
itself does not change returning type so that's why filter(e => e.name !== undefined)
returns (string | undefined)[]
.
You should "cast" e.name
to string to turn (string | undefined)
into string
:
.map(e => e.name as string)