Skip to content

Commit d6e5978

Browse files
authored
fix(eslint-plugin): [no-unnecessary-condition] don't flag optional chaining for union types with an unconstrained type parameters (#10602)
don't flag optional chaining for unconstrained type parameters
1 parent 63135f7 commit d6e5978

File tree

2 files changed

+33
-13
lines changed

2 files changed

+33
-13
lines changed

‎packages/eslint-plugin/src/rules/no-unnecessary-condition.ts

Lines changed: 15 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -304,6 +304,19 @@ export default createRule<Options, MessageId>({
304304
);
305305
}
306306

307+
// Conditional is always necessary if it involves:
308+
// `any` or `unknown` or a naked type variable
309+
function isConditionalAlwaysNecessary(type: ts.Type): boolean {
310+
return tsutils
311+
.unionTypeParts(type)
312+
.some(
313+
part =>
314+
isTypeAnyType(part) ||
315+
isTypeUnknownType(part) ||
316+
isTypeFlagSet(part, ts.TypeFlags.TypeVariable),
317+
);
318+
}
319+
307320
function isNullableMemberExpression(
308321
node: TSESTree.MemberExpression,
309322
): boolean {
@@ -370,18 +383,7 @@ export default createRule<Options, MessageId>({
370383

371384
const type = getConstrainedTypeAtLocation(services, expression);
372385

373-
// Conditional is always necessary if it involves:
374-
// `any` or `unknown` or a naked type variable
375-
if (
376-
tsutils
377-
.unionTypeParts(type)
378-
.some(
379-
part =>
380-
isTypeAnyType(part) ||
381-
isTypeUnknownType(part) ||
382-
isTypeFlagSet(part, ts.TypeFlags.TypeVariable),
383-
)
384-
) {
386+
if (isConditionalAlwaysNecessary(type)) {
385387
return;
386388
}
387389
let messageId: MessageId | null = null;
@@ -813,7 +815,7 @@ export default createRule<Options, MessageId>({
813815
: true;
814816

815817
return (
816-
isTypeFlagSet(type, ts.TypeFlags.Any | ts.TypeFlags.Unknown) ||
818+
isConditionalAlwaysNecessary(type) ||
817819
(isOwnNullable && isNullableType(type))
818820
);
819821
}

‎packages/eslint-plugin/tests/rules/no-unnecessary-condition.test.ts

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,24 @@ function test<T>(t: T | []) {
143143
return t ? 'yes' : 'no';
144144
}
145145
`,
146+
`
147+
function test<T>(arg: T, key: keyof T) {
148+
if (arg[key]?.toString()) {
149+
}
150+
}
151+
`,
152+
`
153+
function test<T>(arg: T, key: keyof T) {
154+
if (arg?.toString()) {
155+
}
156+
}
157+
`,
158+
`
159+
function test<T>(arg: T | { value: string }) {
160+
if (arg?.value) {
161+
}
162+
}
163+
`,
146164

147165
// Boolean expressions
148166
`

0 commit comments

Comments
 (0)