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

Time:06-21

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?

CodePudding user response:

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)

CodePudding user response:

Simple way to fix the message with type casting:

const box: number[] = <number[]>[
  1, 2, 3, 4, undefined
].filter( d => typeof d !== 'undefined')
  • Related