Skip to content

fix(eslint-plugin): [no-unnecessary-condition] false positive on optional private field #9602

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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
21 changes: 13 additions & 8 deletions packages/eslint-plugin/src/rules/no-unnecessary-condition.ts
Original file line number Diff line number Diff line change
Expand Up @@ -211,15 +211,20 @@ export default createRule<Options, MessageId>({
}
const property = node.property;

if (property.type === AST_NODE_TYPES.Identifier) {
Copy link
Contributor Author

@StyleShit StyleShit Jul 21, 2024

Choose a reason for hiding this comment

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

This condition is unnecessary because the property type is Identifier | PrivateIdentifier,
and now we catch both of them

const propertyType = objectType.getProperty(property.name);
if (
propertyType &&
tsutils.isSymbolFlagSet(propertyType, ts.SymbolFlags.Optional)
) {
return true;
}
// Get the actual property name, to account for private properties (this.#prop).
const propertyName = context.sourceCode.getText(property);

const propertyType = objectType
.getProperties()
.find(prop => prop.name === propertyName);

if (
propertyType &&
tsutils.isSymbolFlagSet(propertyType, ts.SymbolFlags.Optional)
) {
return true;
}

return false;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -852,6 +852,19 @@ type Foo = { [key: string]: () => number | undefined } | null;
declare const foo: Foo;
foo?.['bar']()?.toExponential();
`,
{
parserOptions: optionsWithExactOptionalPropertyTypes,
code: `
class ConsistentRand {
#rand?: number;

getCachedRand() {
this.#rand ??= Math.random();
return this.#rand;
}
}
`,
},
],
invalid: [
// Ensure that it's checking in all the right places
Expand Down
Loading