Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(eslint-plugin): [typedef] support nested object destructuring with type annotation #4548

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
25 changes: 24 additions & 1 deletion packages/eslint-plugin/src/rules/typedef.ts
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
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