Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(eslint-plugin): [strict-boolean-expression] false positive for truthy boolean #4275

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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