X Tutup
Skip to content
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 11 additions & 12 deletions src/transformation/visitors/class/members/constructor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,23 +45,22 @@ export function transformConstructorDeclaration(

const classInstanceFields = transformClassInstanceFields(context, instanceFields);

// If there are field initializers and the first statement is a super call,
// move super call between default assignments and initializers
// If there are field initializers and there is a super call somewhere,
// move super call and everything before it to between default assignments and initializers
if (
(constructorFieldsDeclarations.length > 0 || classInstanceFields.length > 0) &&
statement.body &&
statement.body.statements.length > 0
) {
const firstStatement = statement.body.statements[0];
if (
ts.isExpressionStatement(firstStatement) &&
ts.isCallExpression(firstStatement.expression) &&
firstStatement.expression.expression.kind === ts.SyntaxKind.SuperKeyword
) {
const superCall = body.shift();
if (superCall) {
bodyWithFieldInitializers.push(superCall);
}
const superIndex = statement.body.statements.findIndex(
s =>
ts.isExpressionStatement(s) &&
ts.isCallExpression(s.expression) &&
s.expression.expression.kind === ts.SyntaxKind.SuperKeyword
);

if (superIndex !== -1) {
bodyWithFieldInitializers.push(...body.splice(0, superIndex + 1));
}
}

Expand Down
21 changes: 21 additions & 0 deletions test/unit/classes/classes.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,27 @@ test("SubclassConstructor", () => {
`.expectToMatchJsResult();
});

test("SubclassConstructorPropertyInitiailizationSuperOrder", () => {
util.testFunction`
class a {
field: number;
constructor(field: number) {
this.field = field;
}
}
class b extends a {
fieldDouble = this.field * 2;
constructor(field: number) {
const newField = field + 1;
super(newField);
}
}

const result = new b(10);
return [result.field, result.fieldDouble];
`.expectToMatchJsResult();
});

test("Subclass constructor across merged namespace", () => {
util.testModule`
namespace NS {
Expand Down
X Tutup