Skip to content

Bug: [prefer-readonly] False positive if property was assigned after type guard for class properties #7221

Closed
@erengeez

Description

@erengeez

Before You File a Bug Report Please Confirm You Have Done The Following...

  • I have tried restarting my IDE and the issue persists.
  • I have updated to the latest version of the packages.
  • I have searched for related issues and found none that matched my issue.
  • I have read the FAQ and my problem is not listed.

Playground Link

https://typescript-eslint.io/play/#ts=5.1.6&fileType=.tsx&code=MYGwhgzhAEAqCmEAu0DeAoa0AOBXARiAJbDQB288AJhLAPYBC8AIvAGZEVUD8AXObgC2%2BeACcA3Okw5RRAG5gk8cnSQAleGCp0yIAJ4AxOnT4DhYydOyyFSles3bdehmFGmyQkRKlY8hEmglZABZeCQACzoqIzoACgBKNGksIjZoOIBCSKIIADpQSAgABVE6bDEkPQBxXDcqRKSMLBboUXDcUTJJVoBfFKCI3LyyVQ0tHX1Y6ABeaABGHuh%2BqwJiUmCkMMjo11FE5Na0jOyh-NHRQTAQWD0K2vq4nPPKGnomVg4uBKaBrHakJ1ugN%2Bq1niMxo5Ji43LNoAAmJYrPw2RTKQpQUrlSo1OqiBoJfjPaC5QakgBkaHIr1ojBY7E41H4nnMomWhxaAKBZJe1FpHwZXGgmRmc1wZCoguoSN8MnkaJUl2ut3ueIaChAuHgzK8YmgAB9oOLJV9qIToBqtSSYCzvBz-h0uhbrlaRWKJVKqDLekA&eslintrc=N4KABGBEBOCuA2BTAzpAXGUEKQAIBcBPABxQGNoBLY-AWhXkoDt8B6Y6RAM0Wls4CGAEwD2TeIXRRe0EdEjgwAXxBKgA&tsconfig=N4KABGBEDGD2C2AHAlgGwKYCcDyiAuysAdgM6QBcYoEEkJemy0eAcgK6qoDCAFutAGsylAGYBDVCXTgwAXxCygA&tokens=false

Repro Code

class Test {
  public needsToBeDefined?: number;

  private notReadonlyFoo?: number;

  private notReadonlyBar?: number;

  public testMethodFoo() {
    if (!this.classPropertyGuard()) {
      return;
    }
    this.notReadonlyFoo = 1;
  }

  public testMethodBar() {
    if (!this.normalTypeGuard(this.needsToBeDefined)) {
      return;
    }
    this.notReadonlyBar = 2;
  }

  private classPropertyGuard(): this is this & { needsToBeDefined: number } {
    return this.needsToBeDefined !== undefined;
  }

  private normalTypeGuard(value: number | undefined): value is number {
    return value !== undefined;
  }
}

ESLint Config

module.exports = {
  parser: "@typescript-eslint/parser",
  rules: {
    "@typescript-eslint/prefer-readonly": "error"
  },
};

tsconfig

No response

Expected Result

I expected that private notReadonlyFoo?: number; would not report any errors.

Actual Result

@typescript-eslint/prefer-readonly error on the 4th line:

Member 'notReadonlyFoo' is never reassigned; mark it as `readonly`. 4:3 - 4:35

Additional Info

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    accepting prsGo ahead, send a pull request that resolves this issuebugSomething isn't workingpackage: eslint-pluginIssues related to @typescript-eslint/eslint-plugin

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions