Skip to content

Commit

Permalink
support assignment pattern
Browse files Browse the repository at this point in the history
  • Loading branch information
yeonjuan committed Apr 13, 2024
1 parent 95cbd19 commit 012fcfd
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 16 deletions.
Expand Up @@ -93,6 +93,29 @@ export default createRule<[], MessageIds>({
);
}

function isReferenceFromParameter(node: TSESTree.Identifier): boolean {
const scope = context.sourceCode.getScope(node);

const rightRef = scope.references.find(
ref => ref.identifier.name === node.name,
);
return rightRef?.resolved?.defs.at(0)?.type === DefinitionType.Parameter;
}

function isParameterPropertyWithName(
node: TSESTree.Parameter,
name: string,
): boolean {
return (
node.type === AST_NODE_TYPES.TSParameterProperty &&
((node.parameter.type === AST_NODE_TYPES.Identifier && // constructor (public foo) {}
node.parameter.name === name) ||
(node.parameter.type === AST_NODE_TYPES.AssignmentPattern && // constructor (public foo = 1) {}
node.parameter.left.type === AST_NODE_TYPES.Identifier &&
node.parameter.left.name === name))
);
}

return {
ClassBody(): void {
reportInfoStack.push({
Expand Down Expand Up @@ -184,26 +207,14 @@ export default createRule<[], MessageIds>({

if (
right.type !== AST_NODE_TYPES.Identifier ||
leftName !== right.name
leftName !== right.name ||
!isReferenceFromParameter(right)
) {
return;
}

const scope = context.sourceCode.getScope(right);

const rightRef = scope.references.find(
ref => ref.identifier.name === right.name,
);

if (rightRef?.resolved?.defs.at(0)?.type !== DefinitionType.Parameter) {
return;
}

const hasParameterPropety = functionNode.params.some(
p =>
p.type === AST_NODE_TYPES.TSParameterProperty &&
p.parameter.type === AST_NODE_TYPES.Identifier &&
p.parameter.name === right.name,
const hasParameterPropety = functionNode.params.some(param =>
isParameterPropertyWithName(param, right.name),
);

if (hasParameterPropety) {
Expand Down
Expand Up @@ -191,6 +191,22 @@ class Foo {
},
{
code: `
class Foo {
constructor(public foo = '') {
this.foo = foo;
}
}
`,
errors: [
{
line: 4,
column: 5,
messageId: 'unnecessaryAssign',
},
],
},
{
code: `
class Foo {
constructor(public foo: string) {
this.foo ||= foo;
Expand Down

0 comments on commit 012fcfd

Please sign in to comment.