Skip to content
Advertisement

Why does the filter() function not return my expected type-filtered array?

enter image description here

I think I have a misconception with Typescript.
As I understand, after the filter function there will be no undefined in the array. So the return value of filter function will be initialization value of box variable

I can fix it in this way, but I would rather use the same logic as short way as possible:
enter image description here

How can I fix the message?

Advertisement

Answer

It’s annoying, but you have to explicitly set the type predicate in the inner function. Something like this:

const box: number[] = [1, 2, 3, 4, undefined].filter((d): d is number => d !== undefined)

The d is number part tells the compiler that indeed this function ensures that this item is a number. You can also make yourself an utility function

export function isPresent<T>(t: T | undefined | null | void): t is T {
  return t !== undefined && t !== null;
}

const box: number[] = [1, 2, 3, 4, undefined].filter(isPresent)
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement