Skip to content

fix(eslint-plugin): [prefer-readonly] autofixer doesn't add type to property that is mutated in the constructor #10552

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

Conversation

ronami
Copy link
Member

@ronami ronami commented Dec 26, 2024

PR Checklist

Overview

This is a draft PR that attempts to tackle #1056. I've mentioned my thoughts about this at #1056 (comment).

@typescript-eslint
Copy link
Contributor

Thanks for the PR, @ronami!

typescript-eslint is a 100% community driven project, and we are incredibly grateful that you are contributing to that community.

The core maintainers work on this in their personal time, so please understand that it may not be possible for them to review your work immediately.

Thanks again!


🙏 Please, if you or your company is finding typescript-eslint valuable, help us sustain the project by sponsoring it transparently on https://opencollective.com/typescript-eslint.

Copy link

netlify bot commented Dec 26, 2024

Deploy Preview for typescript-eslint ready!

Name Link
🔨 Latest commit 02c3124
🔍 Latest deploy log https://app.netlify.com/sites/typescript-eslint/deploys/678bf9d5cb6ba700083a54a7
😎 Deploy Preview https://deploy-preview-10552--typescript-eslint.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.
Lighthouse
Lighthouse
1 paths audited
Performance: 94 (🔴 down 4 from production)
Accessibility: 100 (no change from production)
Best Practices: 92 (no change from production)
SEO: 98 (no change from production)
PWA: 80 (no change from production)
View the detailed breakdown and full score reports

To edit notification comments on pull requests, go to your Netlify site configuration.

Copy link

nx-cloud bot commented Dec 26, 2024

View your CI Pipeline Execution ↗ for commit 02c3124.

Command Status Duration Result
nx test eslint-plugin ✅ Succeeded 6m 7s View ↗
nx test eslint-plugin --coverage=false ✅ Succeeded 6m 1s View ↗
nx test visitor-keys ✅ Succeeded <1s View ↗
nx run types:build ✅ Succeeded <1s View ↗
nx run-many --target=build --exclude website --... ✅ Succeeded 27s View ↗
nx test utils ✅ Succeeded <1s View ↗
nx run-many --target=clean ✅ Succeeded 12s View ↗
nx test typescript-eslint ✅ Succeeded 4s View ↗
Additional runs (24) ✅ Succeeded ... View ↗

☁️ Nx Cloud last updated this comment at 2025-01-18 19:26:13 UTC

Copy link

codecov bot commented Dec 26, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 87.18%. Comparing base (31be053) to head (02c3124).
Report is 29 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #10552      +/-   ##
==========================================
+ Coverage   87.15%   87.18%   +0.02%     
==========================================
  Files         448      448              
  Lines       15576    15611      +35     
  Branches     4551     4562      +11     
==========================================
+ Hits        13575    13610      +35     
  Misses       1645     1645              
  Partials      356      356              
Flag Coverage Δ
unittest 87.18% <100.00%> (+0.02%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
...ackages/eslint-plugin/src/rules/prefer-readonly.ts 98.28% <100.00%> (+0.42%) ⬆️

const annotation = checker.typeToString(type);

// verify the about-to-be-added type annotation is in-scope
if (tsutils.isTypeFlagSet(initializerType, ts.TypeFlags.EnumLiteral)) {
Copy link
Member Author

Choose a reason for hiding this comment

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

I wrote about this on #1056 (comment), but on some occasions (as far as I know only enums), the rule won't be able to add a type annotation:

// foo.ts
enum Foo {
  Bar,
  Bazz,
}

export const bar = Foo.Bar;

// index.ts
import { bar } from './foo';

export class Test {
  private foo = bar;
}

I chose not to add a type annotation on these cases, but an alternative I think is also valid is to have this be a suggestion instead of an auto-fix.

Would be happy to to hear opinions on this.

Copy link
Member

Choose a reason for hiding this comment

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

I have a vague memory of this coming up once in a while... I think it's fine for now. We don't have any kind of shared/standard plumbing for importing constructs in fixes or suggestions.

@ronami ronami marked this pull request as ready for review December 30, 2024 17:12
JoshuaKGoldberg
JoshuaKGoldberg previously approved these changes Jan 1, 2025
Copy link
Member

@JoshuaKGoldberg JoshuaKGoldberg left a comment

Choose a reason for hiding this comment

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

Animated text saying 'happy new year 2025' with cartoon fireworks

@JoshuaKGoldberg JoshuaKGoldberg added the 1 approval >=1 team member has approved this PR; we're now leaving it open for more reviews before we merge label Jan 1, 2025
@github-actions github-actions bot removed the 1 approval >=1 team member has approved this PR; we're now leaving it open for more reviews before we merge label Jan 1, 2025
@ronami
Copy link
Member Author

ronami commented Jan 3, 2025

Thinking some more about this: The rule will add a type annotation whenever literal widening happens, regardless of whether the property is mutated in the constructor or not.

I'm slightly leaning towards adding a type annotation only when literal widening happens and the property is mutated in the constructor (in addition to an initializer).

@JoshuaKGoldberg JoshuaKGoldberg dismissed their stale review January 6, 2025 15:53

What Ronami said :)

@kirkwaiblinger
Copy link
Member

kirkwaiblinger commented Jan 8, 2025

Thinking some more about this: The rule will add a type annotation whenever literal widening happens, regardless of whether the property is mutated in the constructor or not.

I'm slightly leaning towards adding a type annotation only when literal widening happens and the property is mutated in the constructor (in addition to an initializer).

I'm not sold on this. My concerns are

  • It increases the level of surprise for the user by adding a special case within a special case
  • It changes the public API of the class. This may absolutely be a desired consequence in many cases! But it may also be breaking. This tilts the scales for me more towards the conservative option of conspicuously preserving the original type, and letting the user easily opt in explicitly to the narrower one by removing the type annotation.

My order of most to least preferred approaches for this case would be

  1. (currently implemented) Autofix with original, widened type
  2. Don't autofix. Offer suggestions for both possibilities (very close second, could probably be argued either way between 1 and 2)
  3. Autofix with narrowed type.

But I'll defer to you guys if those points don't sway opinions. It's not a big thing.

@ronami
Copy link
Member Author

ronami commented Jan 9, 2025

Thinking some more about this: The rule will add a type annotation whenever literal widening happens, regardless of whether the property is mutated in the constructor or not.
I'm slightly leaning towards adding a type annotation only when literal widening happens and the property is mutated in the constructor (in addition to an initializer).

I'm not sold on this. My concerns are

  • It increases the level of surprise for the user by adding a special case within a special case
  • It changes the public API of the class. This may absolutely be a desired consequence in many cases! But it may also be breaking. This tilts the scales for me more towards the conservative option of conspicuously preserving the original type, and letting the user easily opt in explicitly to the narrower one by removing the type annotation.

My order of most to least preferred approaches for this case would be

  1. (currently implemented) Autofix with original, widened type
  2. Don't autofix. Offer suggestions for both possibilities (very close second, could probably be argued either way between 1 and 2)
  3. Autofix with narrowed type.

But I'll defer to you guys if those points don't sway opinions. It's not a big thing.

Interesting take!

I didn't put much thought into it, but I agree that it can be confusing. It may seem unclear when the rule would add a type annotation and when it won't. Adding a type annotation whenever literals are involved simplifies how the rule behaves.

I considered the type changing a desired consequence, and I think it will be a breaking change pretty rarely, but it is possible.

For me, the increase in the level of surprise is a big reason to keep it simple and always auto-fix with the widened type 👍

@kirkwaiblinger
Copy link
Member

Oh, I've misunderstood, sorry! - this rule only applies to private/#private propreties. So there isn't a public API concern! In that case I'm on board with only adding the annotation if they actually are mutated 👍

@ronami
Copy link
Member Author

ronami commented Jan 14, 2025

Oh, I've misunderstood, sorry! - this rule only applies to private/#private propreties. So there isn't a public API concern! In that case I'm on board with only adding the annotation if they actually are mutated 👍

@kirkwaiblinger I agree with your point that this change increases the level of surprise for the user by adding a special case within a special case.

I think both options are viable (always adding a type annotation for literals or only when literals are modified in the constructor), and the difference between the two is subtle. I was going back and forth between what I consider the optimal solution here, but I think I'm +1 for adding a type annotation only when necessary, even though it adds some surprise factor.

In my opinion, adding a type annotation may be already somewhat surprising, and adding it only when it's clear why it's necessary makes sense to me.

I've updated the PR to match this 👍

Comment on lines +273 to +275
if (nameNode.type !== AST_NODE_TYPES.Identifier) {
return null;
}
Copy link
Member Author

Choose a reason for hiding this comment

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

To my understanding, this can realistically only be an identifier. This means some cases that should have a type annotation added won't receive it, for example:

class TestOverlappingClassVariable {
  private 'overlappingClassVariable' = 7;

  constructor() {
    this.overlappingClassVariable = 10;
  }
}

This seems like an existing bug that's not necessarily related to this addition. I've opened #10655 as a separate issue to address this.

Copy link
Member

@JoshuaKGoldberg JoshuaKGoldberg left a comment

Choose a reason for hiding this comment

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

LGTM - and such comprehensive unit tests! 😄

Will let you or @kirkwaiblinger merge if you're happy. Edit: it's been a few days and we're about to run a release - merging myself. :shipit:

@JoshuaKGoldberg JoshuaKGoldberg added the 1 approval >=1 team member has approved this PR; we're now leaving it open for more reviews before we merge label Jan 19, 2025
@JoshuaKGoldberg JoshuaKGoldberg merged commit acab0a9 into typescript-eslint:main Jan 27, 2025
64 checks passed
@ronami ronami deleted the prefer-readonly-add-type-annotation branch January 27, 2025 17:16
renovate bot added a commit to andrei-picus-tink/auto-renovate that referenced this pull request Jan 29, 2025
| datasource | package                          | from   | to     |
| ---------- | -------------------------------- | ------ | ------ |
| npm        | @typescript-eslint/eslint-plugin | 8.21.0 | 8.22.0 |
| npm        | @typescript-eslint/parser        | 8.21.0 | 8.22.0 |


## [v8.22.0](https://github.com/typescript-eslint/typescript-eslint/blob/HEAD/packages/eslint-plugin/CHANGELOG.md#8220-2025-01-27)

##### 🩹 Fixes

-   **eslint-plugin:** \[no-unnecessary-template-expression] handle template literal type ([#10612](typescript-eslint/typescript-eslint#10612))
-   **eslint-plugin:** \[prefer-readonly] autofixer doesn't add type to property that is mutated in the constructor ([#10552](typescript-eslint/typescript-eslint#10552))
-   **eslint-plugin:** \[no-extraneous-class] handle accessor keyword ([#10678](typescript-eslint/typescript-eslint#10678))
-   **eslint-plugin:** \[no-shadow] don't report unnecessarily on valid ways of using module augmentation ([#10616](typescript-eslint/typescript-eslint#10616))
-   **eslint-plugin:** \[no-duplicate-type-constituents] handle nested types ([#10638](typescript-eslint/typescript-eslint#10638))
-   **eslint-plugin:** \[prefer-nullish-coalescing] doesn't report on ternary but on equivalent || ([#10517](typescript-eslint/typescript-eslint#10517))

##### ❤️ Thank You

-   mdm317
-   Olivier Zalmanski [@OlivierZal](https://github.com/OlivierZal)
-   Ronen Amiel
-   YeonJuan [@yeonjuan](https://github.com/yeonjuan)

You can read about our [versioning strategy](https://main--typescript-eslint.netlify.app/users/versioning) and [releases](https://main--typescript-eslint.netlify.app/users/releases) on our website.
renovate bot added a commit to andrei-picus-tink/auto-renovate that referenced this pull request Jan 29, 2025
| datasource | package                          | from   | to     |
| ---------- | -------------------------------- | ------ | ------ |
| npm        | @typescript-eslint/eslint-plugin | 8.21.0 | 8.22.0 |
| npm        | @typescript-eslint/parser        | 8.21.0 | 8.22.0 |


## [v8.22.0](https://github.com/typescript-eslint/typescript-eslint/blob/HEAD/packages/eslint-plugin/CHANGELOG.md#8220-2025-01-27)

##### 🩹 Fixes

-   **eslint-plugin:** \[no-unnecessary-template-expression] handle template literal type ([#10612](typescript-eslint/typescript-eslint#10612))
-   **eslint-plugin:** \[prefer-readonly] autofixer doesn't add type to property that is mutated in the constructor ([#10552](typescript-eslint/typescript-eslint#10552))
-   **eslint-plugin:** \[no-extraneous-class] handle accessor keyword ([#10678](typescript-eslint/typescript-eslint#10678))
-   **eslint-plugin:** \[no-shadow] don't report unnecessarily on valid ways of using module augmentation ([#10616](typescript-eslint/typescript-eslint#10616))
-   **eslint-plugin:** \[no-duplicate-type-constituents] handle nested types ([#10638](typescript-eslint/typescript-eslint#10638))
-   **eslint-plugin:** \[prefer-nullish-coalescing] doesn't report on ternary but on equivalent || ([#10517](typescript-eslint/typescript-eslint#10517))

##### ❤️ Thank You

-   mdm317
-   Olivier Zalmanski [@OlivierZal](https://github.com/OlivierZal)
-   Ronen Amiel
-   YeonJuan [@yeonjuan](https://github.com/yeonjuan)

You can read about our [versioning strategy](https://main--typescript-eslint.netlify.app/users/versioning) and [releases](https://main--typescript-eslint.netlify.app/users/releases) on our website.
@github-actions github-actions bot locked as resolved and limited conversation to collaborators Feb 4, 2025
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
1 approval >=1 team member has approved this PR; we're now leaving it open for more reviews before we merge
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Bug: [prefer-readonly] autofixer doesn't add type to property that is mutated in the constructor
3 participants