Disallowed nullish and truthy checks
Fix two TypeScript 5.6 diagnostics by testing a regex against its input and applying a default before negating a boolean.
After upgrading to TypeScript 5.6, you may see errors on a bare regex in a condition or on a dead fallback after ??. Save these two examples as src/checks.ts in a scratch project.
export function isHexColor(input: string) {
if (/^#[0-9a-f]{6}$/i) {
return true
}
return false
}
export function isDisabled(props: { enabled?: boolean }) {
return !props.enabled ?? true
}TypeScript 5.5 accepts both expressions. Run pnpm exec tsc --noEmit src/checks.ts with TypeScript 5.6 or later and no tsconfig.json to see both diagnostics.
src/checks.ts(2,7): error TS2872: This kind of expression is always truthy.
src/checks.ts(9,10): error TS2869: Right operand of ?? is unreachable because the left operand is never nullish.Both functions return true for inputs that should return false. Try isHexColor('red') and isDisabled({}) in Node 22 with type stripping enabled.
What the compiler now reads
TypeScript 5.6 added the check. When the syntax alone shows that a condition always comes out one way, or that the left side of ?? can never be null or undefined, tsc reports it.
The regex is a literal object, and every object is truthy, so the if always passes. The author forgot .test(input).
In the second function, ! binds tighter than ??. The left side is !props.enabled, a boolean, and a boolean is never nullish, so ?? true is dead code.
Test the input and default the boolean
Call the regex on the input. Apply the default before negating enabled.
export function isHexColor(input: string) {
if (/^#[0-9a-f]{6}$/i.test(input)) {
return true
}
return false
}
export function isDisabled(props: { enabled?: boolean }) {
return !(props.enabled ?? true)
}tsc exits 0, isHexColor('red') returns false, and isDisabled({}) returns false because a missing enabled now defaults to on.
If you see TS2869, check which expression sits to the left of ??. A comparison there also produces a boolean, so the fallback cannot run.
Recognize the other diagnostics
The same check reports always-nullish and always-falsy expressions. null ?? 'x' gets TS2871, "This expression is always nullish", and if ("") gets TS2873, "always falsy". Object and array literals, functions and arrow functions count as always truthy in a condition, and tsc also catches if (x => 0) typed in place of x >= 0.
The literals true, false, 0 and 1 stay legal, so while (true) with a break compiles as before.
The check works from syntax alone. Put the same regex in a const and test if (hex), and tsc reports nothing. A function call on the left of ?? passes too, even when that function never returns undefined. When one of these errors appears, look on that line for a missing call or a missing pair of parentheses.