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] support falsy and truthy literals simultaneously #6672

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
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: 50,
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) {} }
kozlovvski marked this conversation as resolved.
Show resolved Hide resolved
`,
errors: [
{
Expand Down Expand Up @@ -1027,6 +1051,28 @@ if (y) {
},
],
},
{
messageId: 'conditionErrorNullableNumber',
line: 5,
column: 45,
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