Skip to content

Commit

Permalink
fix(eslint-plugin): [strict-boolean-expression] support falsy and tru…
Browse files Browse the repository at this point in the history
…thy literals simultaneously (#6672)

* support falsy and truthy literals simultanously

* replace Array.prototype.some condition with Array.prototype.every

* format test cases to match prettier configuration

---------

Co-authored-by: Michał Kozłowski <[email protected]>
  • Loading branch information
kozlovvski and Michał Kozłowski authored Mar 20, 2023
1 parent 58c102d commit 62ef487
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -835,7 +835,9 @@ export default util.createRule<Options, MessageId>({
);

if (strings.length) {
if (strings.some(type => type.isStringLiteral() && type.value !== '')) {
if (
strings.every(type => type.isStringLiteral() && type.value !== '')
) {
variantTypes.add('truthy string');
} else {
variantTypes.add('string');
Expand All @@ -848,8 +850,9 @@ export default util.createRule<Options, MessageId>({
ts.TypeFlags.NumberLike | ts.TypeFlags.BigIntLike,
),
);

if (numbers.length) {
if (numbers.some(type => type.isNumberLiteral() && type.value !== 0)) {
if (numbers.every(type => type.isNumberLiteral() && type.value !== 0)) {
variantTypes.add('truthy number');
} else {
variantTypes.add('number');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -894,6 +894,7 @@ if (y) {
declare const x: string | null; if (x) {}
(x?: string) => !x;
<T extends string | null | undefined>(x: T) => x ? 1 : 0;
function foo(x: '' | 'bar' | null) { if (!x) {} }
`,
errors: [
{
Expand Down Expand Up @@ -956,6 +957,28 @@ if (y) {
},
],
},
{
messageId: 'conditionErrorNullableString',
line: 5,
column: 51,
suggestions: [
{
messageId: 'conditionFixCompareNullish',
output:
" function foo(x: '' | 'bar' | null) { if (x == null) {} }",
},
{
messageId: 'conditionFixDefaultEmptyString',
output:
" function foo(x: '' | 'bar' | null) { if (!(x ?? \"\")) {} }",
},
{
messageId: 'conditionFixCastBoolean',
output:
" function foo(x: '' | 'bar' | null) { if (!Boolean(x)) {} }",
},
],
},
],
}),

Expand All @@ -965,6 +988,7 @@ if (y) {
declare const x: number | null; if (x) {}
(x?: number) => !x;
<T extends number | null | undefined>(x: T) => x ? 1 : 0;
function foo(x: 0 | 1 | null) { if (!x) {} }
`,
errors: [
{
Expand Down Expand Up @@ -1027,6 +1051,28 @@ if (y) {
},
],
},
{
messageId: 'conditionErrorNullableNumber',
line: 5,
column: 46,
suggestions: [
{
messageId: 'conditionFixCompareNullish',
output:
' function foo(x: 0 | 1 | null) { if (x == null) {} }',
},
{
messageId: 'conditionFixDefaultZero',
output:
' function foo(x: 0 | 1 | null) { if (!(x ?? 0)) {} }',
},
{
messageId: 'conditionFixCastBoolean',
output:
' function foo(x: 0 | 1 | null) { if (!Boolean(x)) {} }',
},
],
},
],
}),

Expand Down

0 comments on commit 62ef487

Please sign in to comment.