From 5ac329e16b54256d4d817d1cdbf29e77e0a837f0 Mon Sep 17 00:00:00 2001 From: mdm317 Date: Thu, 18 Sep 2025 13:43:12 +0900 Subject: [PATCH] report only when ternary is top-level inside Boolean --- .../src/rules/prefer-nullish-coalescing.ts | 6 +- .../rules/prefer-nullish-coalescing.test.ts | 84 +++++++++++++------ 2 files changed, 63 insertions(+), 27 deletions(-) diff --git a/packages/eslint-plugin/src/rules/prefer-nullish-coalescing.ts b/packages/eslint-plugin/src/rules/prefer-nullish-coalescing.ts index d611e7b079a9..0956b558b10a 100644 --- a/packages/eslint-plugin/src/rules/prefer-nullish-coalescing.ts +++ b/packages/eslint-plugin/src/rules/prefer-nullish-coalescing.ts @@ -301,7 +301,11 @@ export default createRule({ if ( ignoreBooleanCoercion === true && - isBooleanConstructorContext(node, context) + isBooleanConstructorContext(node, context) && + !( + node.type === AST_NODE_TYPES.ConditionalExpression && + node.parent.type === AST_NODE_TYPES.CallExpression + ) ) { return false; } diff --git a/packages/eslint-plugin/tests/rules/prefer-nullish-coalescing.test.ts b/packages/eslint-plugin/tests/rules/prefer-nullish-coalescing.test.ts index 618d1c244414..e2c5f17c8e5d 100644 --- a/packages/eslint-plugin/tests/rules/prefer-nullish-coalescing.test.ts +++ b/packages/eslint-plugin/tests/rules/prefer-nullish-coalescing.test.ts @@ -1253,32 +1253,6 @@ const test = Boolean(((a = b), b || c)); }, { code: ` -let a: string | true | undefined; -let b: string | boolean | undefined; - -const x = Boolean(a ? a : b); - `, - options: [ - { - ignoreBooleanCoercion: true, - }, - ], - }, - { - code: ` -let a: string | boolean | undefined; -let b: string | boolean | undefined; - -const test = Boolean(!a ? b : a); - `, - options: [ - { - ignoreBooleanCoercion: true, - }, - ], - }, - { - code: ` let a: string | boolean | undefined; let b: string | boolean | undefined; let c: string | boolean | undefined; @@ -5089,6 +5063,64 @@ const x = Boolean(1 + (a ?? b)); let a: string | true | undefined; let b: string | boolean | undefined; +const x = Boolean(a ? a : b); + `, + errors: [ + { + messageId: 'preferNullishOverTernary', + suggestions: [ + { + messageId: 'suggestNullish', + output: ` +let a: string | true | undefined; +let b: string | boolean | undefined; + +const x = Boolean(a ?? b); + `, + }, + ], + }, + ], + options: [ + { + ignoreBooleanCoercion: true, + }, + ], + }, + { + code: ` +let a: string | boolean | undefined; +let b: string | boolean | undefined; + +const test = Boolean(!a ? b : a); + `, + errors: [ + { + messageId: 'preferNullishOverTernary', + suggestions: [ + { + messageId: 'suggestNullish', + output: ` +let a: string | boolean | undefined; +let b: string | boolean | undefined; + +const test = Boolean(a ?? b); + `, + }, + ], + }, + ], + options: [ + { + ignoreBooleanCoercion: true, + }, + ], + }, + { + code: ` +let a: string | true | undefined; +let b: string | boolean | undefined; + declare function f(x: unknown): unknown; if (f(a || b)) {