TypeScript Type Predicates vs Assertion Functions: Why Your Guards May Not Narrow Types

Many TypeScript developers write validation guards that compile successfully but fail to narrow types correctly, leading to silent runtime bugs. The core issue is using plain boolean return types instead of type predicate syntax, which prevents the TypeScript compiler from learning what a validation function actually proves. Type predicates, written as 'value is Type', narrow a parameter's type conditionally when the guard returns true, making them suitable for user input validation where failure is expected. Assertion functions using the 'asserts' keyword instead throw on failure and unconditionally narrow the type for the remainder of the scope, making them better suited for null checks and invariants. Choosing the wrong pattern — or using neither — results in validation code that runs checks but provides no real type safety in practice.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.
Discussion (0)
Log in to join the discussion and vote.
Log in