Skip to content

Commit

Permalink
Merge pull request #114 from edsrzf/fix-arrow-obj-lit
Browse files Browse the repository at this point in the history
Work around jscodeshift arrow function bug
  • Loading branch information
Rudeg authored May 1, 2021
2 parents bbeabb3 + f41f20a commit fd31146
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 20 deletions.
58 changes: 38 additions & 20 deletions packages/ts-migrate-plugins/src/plugins/explicit-any.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,26 +113,44 @@ function replaceTS7006AndTS7008(
node.typeAnnotation == null,
)
.forEach((path) => {
// Special case for single-parameter arrow surrounding parens issue.
if (
j.ArrowFunctionExpression.check(path.parent.node) &&
path.parent.node.params.length === 1
) {
const paramIndex = path.parent.node.params.indexOf(path.node);
path.parent.replace(
j.arrowFunctionExpression.from({
...path.parent.node,
params: [
...path.parent.node.params.slice(0, paramIndex),
j.identifier.from({
...(path.parent.node.params[paramIndex] as Identifier),
typeAnnotation,
}),
...path.parent.node.params.slice(paramIndex + 1),
],
}),
);
} else {
let replaceArrow = false;

const parentNode = path.parent.node;
if (j.ArrowFunctionExpression.check(parentNode)) {
// Special casing to work around jscodeshift bugs.
let { body, params } = parentNode;

// Object literals used as arrow function returns do not have
// parentheses added.
// https://github.com/benjamn/recast/issues/743
if (j.ObjectExpression.check(body)) {
replaceArrow = true;
body = j.objectExpression.from({ ...body });
}

// Make sure to add parentheses around single parameters.
if (params.length === 1) {
replaceArrow = true;
params = [
j.identifier.from({
...(parentNode.params[0] as Identifier),
typeAnnotation,
}),
];
}

if (replaceArrow) {
path.parent.replace(
j.arrowFunctionExpression.from({
...parentNode,
params,
body,
}),
);
}
}

if (!replaceArrow) {
path.get('typeAnnotation').replace(typeAnnotation);
}
});
Expand Down
12 changes: 12 additions & 0 deletions packages/ts-migrate-plugins/tests/src/explicit-any.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,4 +122,16 @@ function f3(this: any) { return () => this; }

expect(result).toBe(`const var1: $TSFixMe = [];`);
});

it('handles arrow functions returning object literals', async () => {
const text = `const fn = (b) => ({});`;

const result = await explicitAnyPlugin.run(
await realPluginParams({
text,
}),
);

expect(result).toBe(`const fn = (b: any) => ({});`);
});
});

0 comments on commit fd31146

Please sign in to comment.