Narrowing in TypeScript with type predicates and discriminated unions
Blog post from Felt
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.