Avoiding casts in TypeScript when filtering an array to not null and not undefined

Avoiding casts in TypeScript when filtering an array to not null and not undefined

__________________________________
problem:

When filtering an array to non-null and not undefined, the resulting type still includes null | undefined.  So, often we need to follow the filter() with a map or a cast.

example:

const myCars: Car | null[] = [];
const ids = (myCars.filter(c => !!c) as Car).map(car => car.id)

__________________________________
solution:

Use a utility function isDefined():

function isDefined(value: T | null | undefined): value is T {
  return value !== null && value !== undefined;
}

example:

const myCars: Car | null[] = [];
const ids = myCars.filter(isDefined).map(car => car.id)

__________________________________

Comments