TypeScript Type Narrowing: A Complete Guide to Union Type Checks
A developer's guide explains how TypeScript narrows union types, using a case where a null check passed earlier still triggers a 'possibly null' error inside a callback. The article argues that type casts with 'as' silence the compiler without resolving the underlying uncertainty, and recommends real narrowing instead. It describes control flow analysis, which tracks each variable's possible types line by line as the code is read. Covered techniques include typeof, instanceof, the in operator, discriminated unions, and user-defined type guards and assertion functions. The guide also lists situations where narrowing is lost, such as closures and repeated function calls, along with fixes for each.
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