Alvaro Aguirre

Filter falsy values from an array with type safety

Using flatMap or ts-reset to remove falsy values from array with type safety

Using flatMap

If we have

const array = [1, 2, undefined, 3, 4, null, 5];

and we want to filter the falsy values we can do

const filter = array.filter(Boolean); // output: 1, 2, 3, 4, 5

or

const filter = array.filter((item) => !!item); // output: 1, 2, 3, 4, 5

and that works good, but, if we are working with typescript we will see that the bad type:

filter-picture

To fix it, we can the array method flatMap: is the combination of a map and a flat operation

const filter = array.flatMap((item) => {
  if (!item) return [];
  return item;
});

or shorter:

const filter = array.flatMap((item) => item || []); // output: 1, 2, 3, 4, 5

and the type is

filter2-picture

Using ts-reset

ts-reset offers extremely strict TypeScript:

Using the first example would work

const filter = array.filter(Boolean); // output: 1, 2, 3, 4, 5