Home / Companies / Felt / Blog / Post Details
Content Deep Dive

Narrowing in TypeScript with type predicates and discriminated unions

Blog post from Felt

Post Details
Company
Date Published
Author
Omar Rizwan, Engineer
Word Count
1,295
Language
English
Hacker News Points
-
Summary

The article explores type narrowing in TypeScript, a process crucial for determining a specific type from a union of possible types, using examples such as async request states and pet objects. It compares three methods for type narrowing: inline checks, type predicates, and discriminated unions, highlighting their respective advantages and disadvantages. While inline checks are quick to implement, they can become complex and are not reusable, and type predicates, though encapsulating logic, require careful management to avoid errors. Discriminated unions are presented as the most robust solution, as they simplify checks, enforce comprehensive handling of all union cases, and enhance code maintainability by leveraging TypeScript's type-checking capabilities. The article argues that discriminated unions, despite requiring more initial modeling effort, provide clearer, more reliable, and maintainable code by explicitly defining possible type combinations and reducing the need for manual updates across the codebase.