Back to Blog
TypeScriptType GuardsType SystemPatterns

TypeScript Type Guards and Narrowing

Master type narrowing in TypeScript. From typeof to instanceof to custom type guards.

B
Bootspring Team
Engineering
July 19, 2021
6 min read

Type guards narrow types at runtime. Here's how to use them effectively.

typeof Guard#

Loading code block...

instanceof Guard#

Loading code block...

in Operator#

Loading code block...

Discriminated Unions#

Loading code block...

Custom Type Guards#

Loading code block...

Assertion Functions#

Loading code block...

Generic Type Guards#

Loading code block...

Narrowing with Control Flow#

Loading code block...

Zod Runtime Validation#

Loading code block...

Best Practices#

Guards: ✓ Use discriminated unions when possible ✓ Keep type guards focused ✓ Use assertion functions for validation ✓ Combine with Zod for runtime safety Patterns: ✓ Prefer 'in' over type assertion ✓ Use exhaustiveness checking ✓ Create reusable type guards ✓ Document complex guards Avoid: ✗ Type assertions without validation ✗ Overly complex type predicates ✗ Ignoring null/undefined ✗ Trusting external data

Conclusion#

Type guards enable safe type narrowing at runtime. Use typeof for primitives, instanceof for classes, and discriminated unions for complex types. Custom type guards with type predicates provide flexibility, while assertion functions enforce invariants. Combine with Zod for robust runtime validation.

Share this article

Help spread the word about Bootspring

Related articles