Conditionals and Branching
Overview
Patterns for conditional logic in TypeScript. This standard covers early returns, if/else for simple conditions, and match from massaman/match (the project's umbrella for 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 match for Multi-Branch Logic
Import match and P from massaman/match (which re-exports ts-pattern). 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 match callback parameter. Never cast to explicit types inside a match arm.
Correct
Incorrect
Match on Shape, Not Categories
Use match 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