Skip to content

Commit

Permalink
fix(eslint-plugin): account for truthy literals in strict-boolean-exp…
Browse files Browse the repository at this point in the history
…ressions
  • Loading branch information
Josh Goldberg committed Mar 29, 2021
1 parent 5414bf2 commit 201ac41
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 15 deletions.
46 changes: 31 additions & 15 deletions packages/eslint-plugin/src/rules/strict-boolean-expressions.ts
Expand Up @@ -308,8 +308,13 @@ export default util.createRule<Options, MessageId>({
return;
}

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

// string
if (is('string')) {
if (is('string') || is('truthy string')) {
if (!options.allowString) {
if (isLogicalNegationExpression(node.parent!)) {
// if (!string)
Expand Down Expand Up @@ -458,7 +463,7 @@ export default util.createRule<Options, MessageId>({
}

// number
if (is('number')) {
if (is('number') || is('truthy number')) {
if (!options.allowNumber) {
if (isArrayLengthExpression(node, typeChecker, parserServices)) {
if (isLogicalNegationExpression(node.parent!)) {
Expand Down Expand Up @@ -701,7 +706,9 @@ export default util.createRule<Options, MessageId>({
| 'nullish'
| 'boolean'
| 'string'
| 'truthy string'
| 'number'
| 'truthy number'
| 'object'
| 'any'
| 'never';
Expand Down Expand Up @@ -731,21 +738,30 @@ export default util.createRule<Options, MessageId>({
variantTypes.add('boolean');
}

if (
types.some(type => tsutils.isTypeFlagSet(type, ts.TypeFlags.StringLike))
) {
variantTypes.add('string');
const strings = types.filter(type =>
tsutils.isTypeFlagSet(type, ts.TypeFlags.StringLike),
);

if (strings.length) {
if (strings.some(type => type.isStringLiteral() && type.value !== '')) {
variantTypes.add('truthy string');
} else {
variantTypes.add('string');
}
}

if (
types.some(type =>
tsutils.isTypeFlagSet(
type,
ts.TypeFlags.NumberLike | ts.TypeFlags.BigIntLike,
),
)
) {
variantTypes.add('number');
const numbers = types.filter(type =>
tsutils.isTypeFlagSet(
type,
ts.TypeFlags.NumberLike | ts.TypeFlags.BigIntLike,
),
);
if (numbers.length) {
if (numbers.some(type => type.isNumberLiteral() && type.value !== 0)) {
variantTypes.add('truthy number');
} else {
variantTypes.add('number');
}
}

if (
Expand Down
Expand Up @@ -133,6 +133,27 @@ if (x) {
tsconfigRootDir: path.join(rootPath, 'unstrict'),
},
},

`
function f(arg: 'a' | null) {
if (arg) console.log(arg);
}
`,
`
function f(arg: 'a' | 'b' | null) {
if (arg) console.log(arg);
}
`,
`
function f(arg: 1 | null) {
if (arg) console.log(arg);
}
`,
`
function f(arg: 1 | 2 | null) {
if (arg) console.log(arg);
}
`,
],

invalid: [
Expand Down

0 comments on commit 201ac41

Please sign in to comment.