Menu

1 / 2

Why `.filter(Boolean)` Doesn't Narrow Types in TypeScript (and how I built an AST fixer for it)

DEV Community·i-am-killvish·6 months ago
#HBHP7KSm
#typescript#javascript#webdev#enter#exit
Reading 0:00
15s threshold

One TypeScript behavior that confused me for a long time was this:

const values = [ 1 , 2 , undefined , 4 ]. filter ( Boolean );

values . map (( v ) => v * 2 );

Enter fullscreen mode

Exit fullscreen mode

At runtime, this works perfectly.

But TypeScript may still complain:

'v' is possibly 'undefined'

Enter fullscreen mode

Exit fullscreen mode

At first glance, this feels wrong.

We already filtered the array.

Why is TypeScript still acting like undefined can exist?

The Important Thing to Understand

TypeScript does not deeply analyze what Boolean() actually does.

Instead, TypeScript mostly relies on:

control-flow analysis

recognized syntax patterns

explicit type predicates

So when you write:

.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.