Skip to content

Disallow truthiness/nullishness checks on syntax that never varies on it - #59217

Merged
Ryan Cavanaugh (RyanCavanaugh) merged 13 commits into
microsoft:mainfrom
RyanCavanaugh:noSuspectTruthyChecks
Jul 22, 2024
Merged

Ryan Cavanaugh (RyanCavanaugh) merged 13 commits into
microsoft:mainfrom
RyanCavanaugh:noSuspectTruthyChecks

Conversation

@RyanCavanaugh

@RyanCavanaugh Ryan Cavanaugh (RyanCavanaugh) commented Jul 10, 2024 •

Copy link
Copy Markdown
Member

Inspired by Matt Bierner (@mjbvz)'s suggestion to disallow if (/regex/), this PR implements a series of checks that mostly overlap with ESLint's no-constant-binary-expression rule, which found some great stuff in their v8.14.

The rule here is that it's an error to check for the truthiness of an expression which has "static truthy semantics", that is, always evaluates to the same truthiness. Examples:

  • if ([someArr]) { is illegal (array literals are always truthy)
  • const foo = { ...someObj } || { } is illegal (object literals are always truthy, even those only spread in null)

The expressions false, true, 0, and 1 are excluded from this check, since code like while (true) {, while(1) {, do { } while (false), if (true || i_am_just_debugging) { are common and unlikely to represent programmer errors.

The same rule is applied to nullishness (the thing ?? checks for). Because ??'s precedence can be surprising, this finds a huge number of "missing parens" bugs.

This check is entirely syntactic, because with noUncheckedIndexAccess off, "hidden" nulls/undefined are idiomatically observed in a variety of places:

function idx(arr: string[], index: number) {
    return arr[index] ?? "out of bounds";
}

A breakdown of all the user test hits can be found at #59217 (comment) (part 1) and #59217 (comment) (part 2).

There are a lot, but 100% of these appear to be legitimate bugs in code, so I don't think it's necessary to add a flag for this.

Loading
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

Author: Team For Uncommitted Bug PR for untriaged, rejected, closed or missing bug

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants