Repository: alangpierce/sucrase (ts)

Issue:
Constructor return type annotations produce invalid JS syntax
Source:
```js
class Foo {
  constructor(): Foo {
    return this;
  }
}
```

Transformed (actual):
```js
class Foo {
  constructor():  {
    return this;
  }
}
```

Transformed (expected):
```js
class Foo {
  constructor()  {
    return this;
  }
}
```

Reproductions:
- TS: https://sucrase.io/#transforms=typescript&code=class%20Foo%20%7B%0A%20%20constructor()%3A%20Foo%20%7B%0A%20%20%20%20return%20this%3B%0A%20%20%7D%0A%7D
- Flow: https://sucrase.io/#transforms=flow&code=class%20Foo%20%7B%0A%20%20constructor()%3A%20Foo%20%7B%0A%20%20%20%20return%20this%3B%0A%20%20%7D%0A%7D

Pull request description:
Remove constructor return type annotations
Fixes #795

This syntax isn't actually valid, but it's easy enough to product working JS to avoid blocking the developer, so this implements that.

Patch:
diff --git a/src/util/getClassInfo.ts b/src/util/getClassInfo.ts
index 80aee82..33f6081 100644
--- a/src/util/getClassInfo.ts
+++ b/src/util/getClassInfo.ts
@@ -278,6 +278,11 @@ function processConstructor(tokens: TokenProcessor): {
   }
   // )
   tokens.nextToken();
+  // Constructor type annotations are invalid, but skip them anyway since
+  // they're easy to skip.
+  while (tokens.currentToken().isType) {
+    tokens.nextToken();
+  }
   let constructorInsertPos = tokens.currentIndex();
 
   // Advance through body looking for a super call.


Test patch:
diff --git a/test/typescript-test.ts b/test/typescript-test.ts
index b1865eb..8c7447c 100644
--- a/test/typescript-test.ts
+++ b/test/typescript-test.ts
@@ -3714,4 +3714,26 @@ describe("typescript transform", () => {
       {transforms: ["typescript"]},
     );
   });
+
+  it("removes return type annotations from constructors", () => {
+    // Constructor return types aren't valid, but we return them anyway since
+    // it's easy and improves the DX when people make the mistake.
+    assertResult(
+      `
+      class A {
+        constructor(): A {
+          return this;
+        }
+      }
+    `,
+      `
+      class A {
+        constructor() {
+          return this;
+        }
+      }
+    `,
+      {transforms: ["typescript"]},
+    );
+  });
 });