diff --git a/packages/eslint-plugin/src/rules/no-unnecessary-condition.ts b/packages/eslint-plugin/src/rules/no-unnecessary-condition.ts index 0a31535797d7..b5819ddb1f0f 100644 --- a/packages/eslint-plugin/src/rules/no-unnecessary-condition.ts +++ b/packages/eslint-plugin/src/rules/no-unnecessary-condition.ts @@ -271,7 +271,10 @@ export default createRule({ if ( isTypeFlagSet( type, - ts.TypeFlags.Any | ts.TypeFlags.Unknown | ts.TypeFlags.TypeParameter, + ts.TypeFlags.Any | + ts.TypeFlags.Unknown | + ts.TypeFlags.TypeParameter | + ts.TypeFlags.TypeVariable, ) ) { return; @@ -345,7 +348,8 @@ export default createRule({ flag |= ts.TypeFlags.Any | ts.TypeFlags.Unknown | - ts.TypeFlags.TypeParameter; + ts.TypeFlags.TypeParameter | + ts.TypeFlags.TypeVariable; // Allow loose comparison to nullish values. if (node.operator === '==' || node.operator === '!=') { diff --git a/packages/eslint-plugin/tests/rules/no-unnecessary-condition.test.ts b/packages/eslint-plugin/tests/rules/no-unnecessary-condition.test.ts index 7c31bf419578..a144c7026c4b 100644 --- a/packages/eslint-plugin/tests/rules/no-unnecessary-condition.test.ts +++ b/packages/eslint-plugin/tests/rules/no-unnecessary-condition.test.ts @@ -253,6 +253,11 @@ function test(a: T) { const t16 = undefined !== a; } `, + ` +function foo(arg: T, key: keyof T): void { + arg[key] == null; +} + `, // Predicate functions ` @@ -317,6 +322,11 @@ function test(a: T) { ` function test(a: T) { return a ?? 'default'; +} + `, + ` +function foo(arg: T, key: keyof T): void { + arg[key] ?? 'default'; } `, // Indexing cases @@ -740,6 +750,11 @@ foo ||= 1; ` declare let foo: number; foo &&= 1; + `, + ` +function foo(arg: T, key: keyof T): void { + arg[key] ??= 'default'; +} `, // https://github.com/typescript-eslint/typescript-eslint/issues/6264 ` @@ -1084,7 +1099,14 @@ function test(a: never) { `, errors: [ruleError(3, 10, 'never')], }, - + { + code: ` +function test(num: T[K]) { + num ?? 'default'; +} + `, + errors: [ruleError(3, 3, 'neverNullish')], + }, // Predicate functions { code: `