Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 15 additions & 13 deletions packages/eslint-plugin/src/rules/no-unnecessary-condition.ts
Original file line number Diff line number Diff line change
Expand Up @@ -304,6 +304,19 @@ export default createRule<Options, MessageId>({
);
}

// Conditional is always necessary if it involves:
// `any` or `unknown` or a naked type variable
function isConditionalAlwaysNecessary(type: ts.Type): boolean {
return tsutils
.unionTypeParts(type)
.some(
part =>
isTypeAnyType(part) ||
isTypeUnknownType(part) ||
isTypeFlagSet(part, ts.TypeFlags.TypeVariable),
);
}

function isNullableMemberExpression(
node: TSESTree.MemberExpression,
): boolean {
Expand Down Expand Up @@ -370,18 +383,7 @@ export default createRule<Options, MessageId>({

const type = getConstrainedTypeAtLocation(services, expression);

// Conditional is always necessary if it involves:
// `any` or `unknown` or a naked type variable
if (
tsutils
.unionTypeParts(type)
.some(
part =>
isTypeAnyType(part) ||
isTypeUnknownType(part) ||
isTypeFlagSet(part, ts.TypeFlags.TypeVariable),
)
) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Praise] Heh, yeah, this was getting a little hard to read inline even before...

if (isConditionalAlwaysNecessary(type)) {
return;
}
let messageId: MessageId | null = null;
Expand Down Expand Up @@ -813,7 +815,7 @@ export default createRule<Options, MessageId>({
: true;

return (
isTypeFlagSet(type, ts.TypeFlags.Any | ts.TypeFlags.Unknown) ||
isConditionalAlwaysNecessary(type) ||
(isOwnNullable && isNullableType(type))
);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,24 @@ function test<T>(t: T | []) {
return t ? 'yes' : 'no';
}
`,
`
function test<T>(arg: T, key: keyof T) {
if (arg[key]?.toString()) {
}
}
`,
`
function test<T>(arg: T, key: keyof T) {
if (arg?.toString()) {
}
}
`,
`
function test<T>(arg: T | { value: string }) {
if (arg?.value) {
}
}
`,

// Boolean expressions
`
Expand Down
Loading