'.filter() does not affect type of array in TypeScript?

check this snippet:

interface Foo {
    id: string;
}

const fooFunc = (arr: Foo[]): Foo[] => arr
    .map((item: Foo): Foo | null => {
        const someCheck = true;

        if (someCheck) {
            return { id: '123' };
        }

        return null;
    })
    .filter((item: Foo | null) => item !== null);

Or click here for a TS Playground link to it: https://pnda.me/TSPlaygroundFilterExample

Type null is not assignable to type Foo

It complains, that it cannot assign null to Foo which is true, BUT: I use .filter() to filter out all possible nulls.

Why is TypeScript still complaining about this? And what can I do about it?

Removing the .filter() on the array has no effect.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source