Search code examples
typescript

Way to tell TypeScript compiler Array.prototype.filter removes certain types from an array?


I am trying to filter null (undefined) element from an array by using Array.prototype.filter but TypeScript compiler does not seem to recognize the derived array of the "filter" function and failed to pass type check.

Assuming following simplified code where I have an array with (number|undefined)[] types and want to filter undefined to fit into a number[] array.

const arry = [1, 2, 3, 4, "5", 6];
const numArry: number[] = arry
    .map((i) => {
        return typeof i === "number" ? i : void 0;
    })
    .filter((i) => i);

Error says:

Type '(number | undefined)[]' is not assignable to type 'number[]'. Type 'number | undefined' is not assignable to type 'number'. Type 'undefined' is not assignable to type 'number'.

I can cast the resulted array to number[] like below knowing filter function removes undefined.

const arry = [1, 2, 3, 4, "5", 6];
const numArry: number[] = (arry
    .map((i) => {
        return typeof i === "number" ? i : void 0;
    })
    .filter((i) => i) as Number[]);

Is there a better way to achieve this other than casting?

Environment: TSC2.1 with strictNullChecks enabled.


Solution

  • Use User-Defined Type Guards feature of TypeScript:

    const arry = [1, 2, 3, 4, "5", 6];
    const numArry: number[] = arry
        .filter((i): i is number => {
            return typeof i === "number";
        });
    // numArry = [1, 2, 3, 4, 6]
    

    Take a look at i is number in the callback function. This trick gives us ability to cast a type of the Array.filter result.