Skip to content

Commit

Permalink
fix(eslint-plugin): [class-literal-property-style] allow getter when …
Browse files Browse the repository at this point in the history
…same key setter exists (#8277)
  • Loading branch information
yeonjuan committed Feb 2, 2024
1 parent 5c253a8 commit 69bd501
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 2 deletions.
24 changes: 22 additions & 2 deletions packages/eslint-plugin/src/rules/class-literal-property-style.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import type { TSESLint, TSESTree } from '@typescript-eslint/utils';
import { AST_NODE_TYPES } from '@typescript-eslint/utils';
import { getSourceCode } from '@typescript-eslint/utils/eslint-utils';

import { createRule } from '../util';
import { createRule, getStaticStringValue } from '../util';

type Options = ['fields' | 'getters'];
type MessageIds =
Expand Down Expand Up @@ -66,6 +66,12 @@ export default createRule<Options, MessageIds>({
},
defaultOptions: ['fields'],
create(context, [style]) {
const sourceCode = getSourceCode(context);

function getMethodName(node: TSESTree.MethodDefinition): string {
return getStaticStringValue(node.key) ?? sourceCode.getText(node.key);
}

return {
...(style === 'fields' && {
MethodDefinition(node): void {
Expand All @@ -89,14 +95,28 @@ export default createRule<Options, MessageIds>({
return;
}

const name = getMethodName(node);

if (node.parent.type === AST_NODE_TYPES.ClassBody) {
const hasDuplicateKeySetter = node.parent.body.some(element => {
return (
element.type === AST_NODE_TYPES.MethodDefinition &&
element.kind === 'set' &&
getMethodName(element) === name
);
});
if (hasDuplicateKeySetter) {
return;
}
}

context.report({
node: node.key,
messageId: 'preferFieldStyle',
suggest: [
{
messageId: 'preferFieldStyleSuggestion',
fix(fixer): TSESLint.RuleFix {
const sourceCode = getSourceCode(context);
const name = sourceCode.getText(node.key);

let text = '';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,48 @@ abstract class Mx {
\`;
}
`,
`
class Mx {
set p1(val) {}
get p1() {
return '';
}
}
`,
`
let p1 = 'p1';
class Mx {
set [p1](val) {}
get [p1]() {
return '';
}
}
`,
`
let p1 = 'p1';
class Mx {
set [/* before set */ p1 /* after set */](val) {}
get [/* before get */ p1 /* after get */]() {
return '';
}
}
`,
`
class Mx {
set ['foo'](val) {}
get foo() {
return '';
}
set bar(val) {}
get ['bar']() {
return '';
}
set ['baz'](val) {}
get baz() {
return '';
}
}
`,
{
code: `
class Mx {
Expand Down

0 comments on commit 69bd501

Please sign in to comment.