Conditionals and Branching
Overview
Patterns for conditional logic in TypeScript. This standard covers early returns, if/else for simple conditions, and ts-pattern for multi-branch matching. Ternaries are banned by the linter. Choosing the right construct keeps logic flat, exhaustive, and easy to follow.
Rules
Use ts-pattern for Multi-Branch Logic
Use ts-pattern for conditional logic with 2+ branches. It provides exhaustiveness checking and better readability than switch statements or nested ternaries.
Correct
Incorrect
Use Inferred Types from Callbacks
Always use the inferred type from the ts-pattern callback parameter. Never cast to explicit types inside a match arm.
Correct
Incorrect
Match on Shape, Not Categories
Use ts-pattern directly to match on object shape rather than creating intermediate categorization functions.
Correct
Incorrect
Always Use .exhaustive()
Use .exhaustive() to ensure all cases are handled at compile time. Reserve .otherwise() for genuinely open-ended matches.
Correct
Incorrect
Use if/else for Simple Conditions
Use if/else for simple boolean conditions. Ternaries are not permitted by the linter. Extract the logic into a function to keep bindings const.
Correct
Incorrect
Use Early Returns for Guards
Use if statements with early returns for guard clauses that reject invalid state before the main logic.
Correct
Incorrect
Resources
References
- Types -- Discriminated unions for type-safe matching