Search code examples
javascripttypescript

Filtering non null from array in typesctipt


I have this code:

let x1: (number | null)[] = [null, 1, 2, 3, null];
let x2: number[] = x1.filter( o => o !== null );

I am trying to filter the non-null value using filter. VS code is giving me this error

Type '(number | null)[]' is not assignable to type 'number[]'. Type 'number | null' is not assignable to type 'number'. Type 'null' is not assignable to type 'number'.ts(2322)

Thanks in advance.


Solution

  • The filter() method for arrays only narrows if the callback you pass it is a function that returns a type predicate (of the form arg is Type). In TypeScript 5.4 and below you need to manually annotate that return type:

    // TS5.4 and below
    let x1: (number | null)[] = [null, 1, 2, 3, null];
    let x2: number[] = x1.filter((o): o is number => o !== null); // okay
    

    But starting in TypeScript 5.5, type predicates will be inferred from the function implementation, as implemented in microsoft/TypeScript#57465, meaning your code will suddenly start working as-is:

    // TS5.5 and above
    let x1: (number | null)[] = [null, 1, 2, 3, null];
    let x2: number[] = x1.filter(o => o !== null); // okay
    

    Playground link to code