been staring at this code for while now..
Need some help
I have this filter, and im trying to remove undefined objects from array:
.then((items) => {
const filtered = items.map( i => {
if (i !== undefined) {
return i
}
})
updateState(filtered, query)
});
Followed by the filtered giving error:
Argument of type '({ service: Service; results: Card[]; } | undefined)[]' is not assignable to parameter of type 'SearchResult[]'.
Type '{ service: Service; results: Card[]; } | undefined' is not assignable to type 'SearchResult'.
Type 'undefined' is not assignable to type 'SearchResult'.
when i try to pass it to updateState() function.
Shouldn't the filter do just that? remove the undefined items from the array.. What is going on here?
EDIT: Even filtering with type assertion gives the same error..
const filtered: SearchResult[] = results.filter( i => i as SearchResult)
With same result..
Thanks
CodePudding user response:
If you do not return a value from the map
function, it returns undefined
, so the return from your current code for an undefined
value is still undefined
.
You can get your desired result by using filter instead of map, or by returning a default value other than undefined
when your map encounters undefined
.
CodePudding user response:
So, it turns out Typescript is not able to figure the type of return here..
after long while abusing google searches with different keywords i came up with this line
const filtered: SearchResult[] = results.filter( (i): i is SearchResult => !!i)
I got it from this blog post: https://www.benmvp.com/blog/filtering-undefined-elements-from-array-typescript/
Have a nice day everyone!