Skip to content

Commit

Permalink
fix(eslint-plugin): [strict-boolean-expression] false positive for tr…
Browse files Browse the repository at this point in the history
…uthy boolean (#4275)
  • Loading branch information
lonyele committed Dec 15, 2021
1 parent 9213c6b commit 72c2e41
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 6 deletions.
25 changes: 19 additions & 6 deletions packages/eslint-plugin/src/rules/strict-boolean-expressions.ts
Expand Up @@ -233,7 +233,7 @@ export default util.createRule<Options, MessageId>({
wantedTypes.every(type => types.has(type));

// boolean
if (is('boolean')) {
if (is('boolean') || is('truthy boolean')) {
// boolean is always okay
return;
}
Expand All @@ -251,6 +251,11 @@ export default util.createRule<Options, MessageId>({
return;
}

// Known edge case: boolean `true` and nullish values are always valid boolean expressions
if (is('nullish', 'truthy boolean')) {
return;
}

// nullable boolean
if (is('nullish', 'boolean')) {
if (!options.allowNullableBoolean) {
Expand Down Expand Up @@ -708,6 +713,7 @@ export default util.createRule<Options, MessageId>({
type VariantType =
| 'nullish'
| 'boolean'
| 'truthy boolean'
| 'string'
| 'truthy string'
| 'number'
Expand All @@ -732,12 +738,19 @@ export default util.createRule<Options, MessageId>({
) {
variantTypes.add('nullish');
}
const booleans = types.filter(type =>
tsutils.isTypeFlagSet(type, ts.TypeFlags.BooleanLike),
);

if (
types.some(type =>
tsutils.isTypeFlagSet(type, ts.TypeFlags.BooleanLike),
)
) {
// If incoming type is either "true" or "false", there will be one type
// object with intrinsicName set accordingly
// If incoming type is boolean, there will be two type objects with
// intrinsicName set "true" and "false" each because of tsutils.unionTypeParts()
if (booleans.length === 1) {
tsutils.isBooleanLiteralType(booleans[0], true)
? variantTypes.add('truthy boolean')
: variantTypes.add('boolean');
} else if (booleans.length === 2) {
variantTypes.add('boolean');
}

Expand Down
Expand Up @@ -167,6 +167,20 @@ function f(arg: 1 | null) {
`
function f(arg: 1 | 2 | null) {
if (arg) console.log(arg);
}
`,
`
interface Options {
readonly enableSomething?: true;
}
function f(opts: Options): void {
if (opts.enableSomething) console.log('Do something');
}
`,
`
declare const x: true | null;
if (x) {
}
`,
{
Expand Down

0 comments on commit 72c2e41

Please sign in to comment.