Menu

Surprising type of a filtered array

Reading 0:00
15s threshold

I have an array that contains a mix of number and string values, in other words its type is (string | number)[]:

a = [0, 1, 2, NaN, 'x'] 

I wanted to filter only the numeric values 0, 1 and 2 that are not NaN, so I used a perfectly ordinary filter() call:

numbers = a.filter(n => typeof n === 'number' && !isNaN(n)) 

However, to my surprise the array "numbers" still has type (string | number)[], which logically makes no sense. No string value can pass the filter.

However, if I split the "and" expression to two separate filter() calls the array does get type number[]:

numbers = a.filter(n => typeof n === 'number').filter(n => !isNaN(n)) 

What's the reason for this surprising behaviour? Is there a general TypeScript principle that applies here?

I'm experienced in JavaScript, however not super well-versed in TypeScript.

submitted by /u/Antti5
[link] [comments]