Menu

Post image 1
Post image 2
1 / 2
0

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

DEV Community·i-am-killvish·19 days ago
#HBHP7KSm
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: . filter ( Boolean ) Enter fullscreen mode Exit fullscreen mode TypeScript mainly sees: "A function returning boolean" Enter fullscreen mode Exit fullscreen mode not: "This removes undefined and null values from the array" Enter fullscreen mode Exit fullscreen mode That relationship gets lost.…

Continue reading — create a free account

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

Read More