#Type return value of array.filter

21 messages · Page 1 of 1 (latest)

foggy flame
#

Hi, I'm having a little trouble with .filter while specifying the return value. I have something like this:

[
    this.getHexagonAt(col, row, 'RIGHT'),
    this.getHexagonAt(col, row, 'TOP_RIGHT'),
    this.getHexagonAt(col, row, 'TOP_LEFT'),
    this.getHexagonAt(col, row, 'LEFT'),
    this.getHexagonAt(col, row, 'BOTTOM_LEFT'),
    this.getHexagonAt(col, row, 'BOTTOM_RIGHT')
].filter(Boolean);

Where getHexagonAt return type is Hexagon|null. I'm passing the Boolean function to filter out all null values, so that all I get is an array with Hexagon (or empty). But TypeScript keeps yelling at me saying that the return value is possibly null.

The code runs correctly and as expected, it's just the typing that is giving me trouble. How can I work around this? Thanks!

modern mural
#

you'll have to provide a typeguard as a function

[].filter((hex): hex is Hexagon => hex);
#

btw, why not use an array of those 6 positions and use map to get the hexagons?

foggy flame
#

I'm using filter because I may not get all of the 6 hexagons since some of them may be null. With map I would still get 6 items in the array regardless of whether I can work with them or not.

#

As for the safeguard, I'm not sure I understand how that works. In that example I'd be telling it that hex in the callback is a Hexagon but that may not be so.

#

The tricky part is the return type.

modern mural
modern mural
#

it returns a boolean, and if the value is true, then hex is a Hexagon, and ts can narrow that

foggy flame
#

mmm what would be the right syntax for that? Sorry I'm still not sure how to implement this

modern mural
#

uh, i already showed it

eager isleBOT
foggy flame
#

Oh

#

It works, I thought that was pseudo code 😄

#

I didn't know you couldspecify the type like that

modern mural
#

lmao

foggy flame
#

Thanks a lot 😄

#

I'll look it up later how this works exactly, very useful to know

modern mural