Perhaps a typical TypeScript question. Let's take a look at this simple filtering code:
interface Person {
id: number;
name?: string;
}
const people: Person[] = [
{ id: 1, name: 'Alice' },
{ id: 2 },
{ id: 3, name: 'Bob' },
];
people
.filter(person => Boolean(person.name))
// Why does it say 'Object is possibly undefined'?
.map(person => console.log(person.name.length));
I have added a filter to remove undefined
in the filter
block, but the compiler still warns that Object is possibly 'undefined'
.
Can someone explain why TypeScript behaves like this? And are there any good workarounds for this issue.
NOTE: I need to use the
strictNullChecks
option.
Thank you.