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

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.

Leave a Comment

tech