Skip to content

Commit

Permalink
fix: support nested object deconstructuring with type annotation (#4548)
Browse files Browse the repository at this point in the history
  • Loading branch information
lonyele authored Feb 13, 2022
1 parent 5b7d8df commit 4da9278
Show file tree
Hide file tree
Showing 2 changed files with 82 additions and 1 deletion.
25 changes: 24 additions & 1 deletion packages/eslint-plugin/src/rules/typedef.ts
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,25 @@ export default util.createRule<[Options], MessageIds>({
);
}

function isAncestorHasTypeAnnotation(
node: TSESTree.ObjectPattern,
): boolean {
let ancestor = node.parent;

while (ancestor) {
if (
ancestor.type === AST_NODE_TYPES.ObjectPattern &&
ancestor.typeAnnotation
) {
return true;
}

ancestor = ancestor.parent;
}

return false;
}

return {
...(arrayDestructuring && {
ArrayPattern(node): void {
Expand Down Expand Up @@ -193,7 +212,11 @@ export default util.createRule<[Options], MessageIds>({
}),
...(objectDestructuring && {
ObjectPattern(node): void {
if (!node.typeAnnotation && !isForOfStatementContext(node)) {
if (
!node.typeAnnotation &&
!isForOfStatementContext(node) &&
!isAncestorHasTypeAnnotation(node)
) {
report(node);
}
},
Expand Down
58 changes: 58 additions & 0 deletions packages/eslint-plugin/tests/rules/typedef.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,26 @@ ruleTester.run('typedef', rule, {
},
],
},
{
code: `
const {
id,
details: {
name: {
first,
middle,
last,
forTest: { moreNested },
},
},
}: User = getUser();
`,
options: [
{
objectDestructuring: true,
},
],
},
// Function parameters
'function receivesNumber(a: number): void {}',
'function receivesStrings(a: string, b: string): void {}',
Expand Down Expand Up @@ -516,6 +536,44 @@ class ClassName {
},
],
},
{
code: `
const {
id,
details: {
name: {
first,
middle,
last,
forTest: { moreNested },
},
},
} = getUser();
`,
errors: [
{
data: { name: 'first' },
messageId: 'expectedTypedef',
},
{
data: { name: 'middle' },
messageId: 'expectedTypedef',
},
{
data: { name: 'last' },
messageId: 'expectedTypedef',
},
{
data: { name: 'moreNested' },
messageId: 'expectedTypedef',
},
],
options: [
{
objectDestructuring: true,
},
],
},
// Arrow parameters
{
code: 'const receivesNumber = (a): void => {};',
Expand Down

0 comments on commit 4da9278

Please sign in to comment.