Skip to content

Commit

Permalink
Fix crash with TypeScript overloaded constructors (#340)
Browse files Browse the repository at this point in the history
Fixes #334

Constructors without bodies were correctly being marked as type tokens, but the
class transformation code (to implement class fields and TS fields defined in
constructor params) was incorrectly viewing it as a real constructor. Now, when
checking if something matches the constructor keyword, we also make sure it's
not a type token.
  • Loading branch information
alangpierce authored Nov 18, 2018
1 parent f9aca57 commit e460053
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
7 changes: 5 additions & 2 deletions src/util/getClassInfo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ export default function getClassInfo(

tokens.nextToken();
while (!tokens.matchesContextIdAndLabel(tt.braceR, classContextId)) {
if (tokens.matchesContextual(ContextualKeyword._constructor)) {
if (tokens.matchesContextual(ContextualKeyword._constructor) && !tokens.currentToken().isType) {
({constructorInitializers, constructorInsertPos} = processConstructor(tokens));
} else if (tokens.matches1(tt.semi)) {
rangesToRemove.push({start: tokens.currentIndex(), end: tokens.currentIndex() + 1});
Expand All @@ -83,7 +83,10 @@ export default function getClassInfo(
}
tokens.nextToken();
}
if (tokens.matchesContextual(ContextualKeyword._constructor)) {
if (
tokens.matchesContextual(ContextualKeyword._constructor) &&
!tokens.currentToken().isType
) {
({constructorInitializers, constructorInsertPos} = processConstructor(tokens));
continue;
}
Expand Down
19 changes: 19 additions & 0 deletions test/typescript-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1251,4 +1251,23 @@ describe("typescript transform", () => {
`,
);
});

it("allows overloads for constructors", () => {
assertTypeScriptResult(
`
class A {
constructor(s: string)
constructor(n: number)
constructor(sn: string | number) {}
}
`,
`"use strict";
class A {
constructor(sn) {}
}
`,
);
});
});

0 comments on commit e460053

Please sign in to comment.