TypeScript Type Guards
Grades switches over a union that lack an exhaustiveness check, and reports the narrowing patterns a file uses.
Union types are most useful when narrowed cleanly. Type predicates (x is T), discriminated unions (type: 'a' | 'b'), and exhaustiveness checks turn unions from runtime ambiguity into compile-time safety.
Narrowing itself is reported, not graded. In a program that compiles, a union-typed value is either narrowed before a member-specific use or passed through untouched; the compiler rejects everything else, and the escapes (as, !) are charged by ts-type-safety. What the compiler does not enforce is exhaustiveness: a switch over a union with no default branch silently skips a member added later, unless the switch is the last statement of a function whose declared return type forces every case to return. Each such switch costs 10 points, up to 30, and is named by the no-exhaustiveness-check finding. A switch with a default branch is not reported, whether the branch hands the value to something typed never or returns a fallback: the fallback is a decision about every other member, which is also where typescript-eslint's switch-exhaustiveness-check draws the line by default.
A switch is known to be over a union when the type of the switched value can be read from the file; when it cannot (an imported type), a property with a conventional discriminant name (kind, type, tag, variant, status, action, event, role) is taken as one. A file that holds no union-typed value at run time and narrows nothing, such as a types-only module, is not applicable and does not enter the plugin score.
Severity guide
- info
- A positive narrowing pattern is in use, or an object union would benefit from a discriminant.
- warning
- A switch over a union has no default branch and no compiler-enforced return: a member added later is silently skipped.
- critical
- Not currently emitted by this analysis.
Remediation
Add type predicates for runtime narrowing; convert union types to discriminated unions where appropriate; add exhaustiveness assertions.
Add type predicates for runtime narrowing; convert union types to discriminated unions where appropriate; add exhaustiveness assertions.