Skip to content

Commit 84613e5

Browse files
authored
fix: properly insert async keyword in arrow function (#1597)
1 parent 04a1679 commit 84613e5

File tree

2 files changed

+14
-4
lines changed

2 files changed

+14
-4
lines changed

packages/ts-morph/src/compiler/ast/base/ModifierableNode.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,8 @@ export function ModifierableNode<T extends Constructor<ModifierableNodeExtension
161161
function getInitialInsertPos() {
162162
if (modifiers.length > 0)
163163
return modifiers[0].getStart();
164+
if (node.getKind() === SyntaxKind.ArrowFunction)
165+
return node.getStart();
164166
for (const child of node._getChildrenIterator()) {
165167
// skip over any initial syntax lists (ex. decorators) or js docs
166168
if (child.getKind() === SyntaxKind.SyntaxList || ts.isJSDocCommentContainingNode(child.compilerNode))

packages/ts-morph/src/tests/compiler/ast/base/asyncableNodeTests.ts

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
import { nameof } from "@ts-morph/common";
1+
import { nameof, SyntaxKind } from "@ts-morph/common";
22
import { expect } from "chai";
3-
import { AsyncableNode, FunctionDeclaration } from "../../../../compiler";
3+
import { AsyncableNode, FunctionDeclaration, Node, VariableStatement } from "../../../../compiler";
44
import { AsyncableNodeStructure } from "../../../../structures";
55
import { getInfoFromText } from "../../testHelpers";
66

@@ -43,8 +43,10 @@ describe("AsyncableNode", () => {
4343

4444
describe(nameof<AsyncableNode>("setIsAsync"), () => {
4545
function doTest(text: string, value: boolean, expected: string) {
46-
const { firstChild, sourceFile } = getInfoFromText<FunctionDeclaration>(text);
47-
firstChild.setIsAsync(value);
46+
let { firstChild, sourceFile } = getInfoFromText(text);
47+
if (firstChild.getKind() === SyntaxKind.VariableStatement)
48+
firstChild = (firstChild as VariableStatement).getDeclarations()[0].getInitializerOrThrow();
49+
(firstChild as any as AsyncableNode).setIsAsync(value);
4850
expect(sourceFile.getText()).to.equal(expected);
4951
}
5052

@@ -55,6 +57,12 @@ describe("AsyncableNode", () => {
5557
it("should set as not async when async", () => {
5658
doTest("async function Identifier() {}", false, "function Identifier() {}");
5759
});
60+
61+
it("should handle arrow function", () => {
62+
doTest("const f = a => a * 2;", true, "const f = async a => a * 2;");
63+
doTest("const f = async a => a * 2;", true, "const f = async a => a * 2;");
64+
doTest("const f = async a => a * 2;", false, "const f = a => a * 2;");
65+
});
5866
});
5967

6068
describe(nameof<FunctionDeclaration>("getStructure"), () => {

0 commit comments

Comments
 (0)