Skip to content

Commit

Permalink
fix(eslint-plugin): [strict-boolean-expressions] handle truthy enums (#…
Browse files Browse the repository at this point in the history
…6618)

fix: handle truthy enums in allowNullableEnum
  • Loading branch information
adamaveray committed Mar 18, 2023
1 parent a1a20b3 commit 0d0639f
Show file tree
Hide file tree
Showing 2 changed files with 98 additions and 1 deletion.
Expand Up @@ -726,7 +726,12 @@ export default util.createRule<Options, MessageId>({
}

// nullable enum
if (is('nullish', 'number', 'enum') || is('nullish', 'string', 'enum')) {
if (
is('nullish', 'number', 'enum') ||
is('nullish', 'string', 'enum') ||
is('nullish', 'truthy number', 'enum') ||
is('nullish', 'truthy string', 'enum')
) {
if (!options.allowNullableEnum) {
if (isLogicalNegationExpression(node.parent!)) {
context.report({
Expand Down
Expand Up @@ -166,6 +166,38 @@ ruleTester.run('strict-boolean-expressions', rule, {
`,
options: [{ allowNullableEnum: true }],
},
{
code: `
enum ExampleEnum {
This = 1,
That = 2,
}
const rand = Math.random();
let theEnum: ExampleEnum | null = null;
if (rand < 0.3) {
theEnum = ExampleEnum.This;
}
if (!theEnum) {
}
`,
options: [{ allowNullableEnum: true }],
},
{
code: `
enum ExampleEnum {
This = 'one',
That = 'two',
}
const rand = Math.random();
let theEnum: ExampleEnum | null = null;
if (rand < 0.3) {
theEnum = ExampleEnum.This;
}
if (!theEnum) {
}
`,
options: [{ allowNullableEnum: true }],
},
{
code: `
declare const x: string[] | null;
Expand Down Expand Up @@ -1149,6 +1181,66 @@ if (y) {
}
`,
},
{
options: [{ allowNullableEnum: false }],
code: `
enum ExampleEnum {
This = 'one',
That = 'two',
}
const theEnum = Math.random() < 0.3 ? ExampleEnum.This : null;
if (!theEnum) {
}
`,
errors: [
{
line: 7,
column: 14,
messageId: 'conditionErrorNullableEnum',
endLine: 7,
endColumn: 21,
},
],
output: `
enum ExampleEnum {
This = 'one',
That = 'two',
}
const theEnum = Math.random() < 0.3 ? ExampleEnum.This : null;
if (theEnum == null) {
}
`,
},
{
options: [{ allowNullableEnum: false }],
code: `
enum ExampleEnum {
This = 1,
That = 2,
}
const theEnum = Math.random() < 0.3 ? ExampleEnum.This : null;
if (!theEnum) {
}
`,
errors: [
{
line: 7,
column: 14,
messageId: 'conditionErrorNullableEnum',
endLine: 7,
endColumn: 21,
},
],
output: `
enum ExampleEnum {
This = 1,
That = 2,
}
const theEnum = Math.random() < 0.3 ? ExampleEnum.This : null;
if (theEnum == null) {
}
`,
},
// any in boolean context
...batchedSingleLineTests<MessageId, Options>({
code: noFormat`
Expand Down

0 comments on commit 0d0639f

Please sign in to comment.