Back to Blog
TypeScriptTypesType GuardsNarrowing

TypeScript Narrowing Techniques

Master TypeScript type narrowing. From type guards to discriminated unions to assertion functions.

B
Bootspring Team
Engineering
September 18, 2020
7 min read

Type narrowing refines types within conditional blocks. Here's how to use it effectively.

Basic Type Guards#

Loading code block...

Truthiness Narrowing#

Loading code block...

Equality Narrowing#

Loading code block...

in Operator Narrowing#

Loading code block...

Custom Type Guards#

Loading code block...

Discriminated Unions#

Loading code block...

Assertion Functions#

Loading code block...

Narrowing with Control Flow#

Loading code block...

Advanced Patterns#

Loading code block...

Best Practices#

Type Guards: ✓ Use typeof for primitives ✓ Use instanceof for classes ✓ Use in for object properties ✓ Use discriminant for unions Custom Guards: ✓ Return type predicate (is) ✓ Keep guards simple ✓ Throw for assertions ✓ Test edge cases Control Flow: ✓ Use early returns ✓ Handle all union members ✓ Use never for exhaustiveness ✓ Be explicit about null Avoid: ✗ Type assertions (as) instead of guards ✗ Complex nested conditions ✗ Ignoring null/undefined ✗ Assuming truthy means defined

Conclusion#

TypeScript narrowing enables type-safe conditional logic. Use built-in type guards for common cases, custom type predicates for complex checks, and discriminated unions for state management. Always handle all union members and use exhaustiveness checking to catch missing cases.

Share this article

Help spread the word about Bootspring

Related articles