How to tell TypeScript compiler to remove certain types from an array with Array.prototype.filter?

Sometimes, we want to tell TypeScript compiler to remove certain types from an array with Array.prototype.filter.

In this article, we’ll look at how to tell TypeScript compiler to remove certain types from an array with Array.prototype.filter.

How to tell TypeScript compiler to remove certain types from an array with Array.prototype.filter?

To tell TypeScript compiler to remove certain types from an array with Array.prototype.filter, we can create our own type guard function and use that as the filter method’s callback.

For instance, we write

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

to call arr.filter with

(i): i is number => {
  return typeof i === "number";
}

i is number is a return type that returns a boolean that tells us if the parameter i is a number or not.

Then numArr would be an array with only numbers.

Conclusion

To tell TypeScript compiler to remove certain types from an array with Array.prototype.filter, we can create our own type guard function and use that as the filter method’s callback.