Skip to content

Commit

Permalink
fix(eslint-plugin): [prefer-readonly] correct issue with anonymus fun…
Browse files Browse the repository at this point in the history
…ctions (#4974)

* fix(eslint-plugin): [prefer-readonly] correct issue with anonymus functions #2590

* test(eslint-plugin): add missing invalid case

Co-authored-by: Brad Zacher <brad.zacher@gmail.com>
  • Loading branch information
armano2 and bradzacher committed May 23, 2022
1 parent 1012e0b commit 952e2f0
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 2 deletions.
8 changes: 6 additions & 2 deletions packages/eslint-plugin/src/rules/prefer-readonly.ts
Expand Up @@ -270,8 +270,12 @@ class ClassScope {
classNode: ts.ClassLikeDeclaration,
private readonly onlyInlineLambdas?: boolean,
) {
this.checker = checker;
this.classType = checker.getTypeAtLocation(classNode);
const classType = checker.getTypeAtLocation(classNode);
if (tsutils.isIntersectionType(classType)) {
this.classType = classType.types[0];
} else {
this.classType = classType;
}

for (const member of classNode.members) {
if (ts.isPropertyDeclaration(member)) {
Expand Down
38 changes: 38 additions & 0 deletions packages/eslint-plugin/tests/rules/prefer-readonly.test.ts
Expand Up @@ -292,6 +292,19 @@ class Foo {
},
{
code: `
function ClassWithName<TBase extends new (...args: any[]) => {}>(Base: TBase) {
return class extends Base {
private _name: string;
public test(value: string) {
this._name = value;
}
};
}
`,
},
{
code: `
class Foo {
private value: Record<string, number> = {};
Expand Down Expand Up @@ -704,5 +717,30 @@ class Foo {
}
`,
},
{
code: `
function ClassWithName<TBase extends new (...args: any[]) => {}>(Base: TBase) {
return class extends Base {
private _name: string;
};
}
`,
output: `
function ClassWithName<TBase extends new (...args: any[]) => {}>(Base: TBase) {
return class extends Base {
private readonly _name: string;
};
}
`,
errors: [
{
data: {
name: '_name',
},
line: 4,
messageId: 'preferReadonly',
},
],
},
],
});

0 comments on commit 952e2f0

Please sign in to comment.