Skip to content

Commit 61bfff3

Browse files
authored
Put preceding statements for class fields in the constructor instead of file scope (#1209)
1 parent 78d7cf7 commit 61bfff3

File tree

2 files changed

+17
-1
lines changed

2 files changed

+17
-1
lines changed

src/transformation/visitors/class/members/constructor.ts

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import * as ts from "typescript";
22
import * as lua from "../../../../LuaAST";
33
import { TransformationContext } from "../../../context";
44
import { createSelfIdentifier } from "../../../utils/lua-ast";
5+
import { transformInPrecedingStatementScope } from "../../../utils/preceding-statements";
56
import { popScope, pushScope, ScopeType } from "../../../utils/scope";
67
import { transformFunctionBodyContent, transformFunctionBodyHeader, transformParameters } from "../../function";
78
import { transformIdentifier } from "../../identifier";
@@ -43,7 +44,9 @@ export function transformConstructorDeclaration(
4344
// Check for field declarations in constructor
4445
const constructorFieldsDeclarations = statement.parameters.filter(p => p.modifiers !== undefined);
4546

46-
const classInstanceFields = transformClassInstanceFields(context, instanceFields);
47+
const [fieldsPrecedingStatements, classInstanceFields] = transformInPrecedingStatementScope(context, () =>
48+
transformClassInstanceFields(context, instanceFields)
49+
);
4750

4851
// If there are field initializers and the first statement is a super call,
4952
// move super call between default assignments and initializers
@@ -78,6 +81,7 @@ export function transformConstructorDeclaration(
7881
// else { TypeScript error: A parameter property may not be declared using a binding pattern }
7982
}
8083

84+
bodyWithFieldInitializers.push(...fieldsPrecedingStatements);
8185
bodyWithFieldInitializers.push(...classInstanceFields);
8286

8387
bodyWithFieldInitializers.push(...body);

test/unit/precedingStatements.spec.ts

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -623,3 +623,15 @@ test("else if", () => {
623623
return i;
624624
`.expectToMatchJsResult();
625625
});
626+
627+
// https://github.com/TypeScriptToLua/TypeScriptToLua/issues/1208
628+
test("class member initializers", () => {
629+
util.testFunction`
630+
class MyClass {
631+
myField = false ?? true;
632+
constructor(public foo: number = 0 ?? 5) {}
633+
}
634+
const inst = new MyClass();
635+
return [inst.myField, inst.foo];
636+
`.expectToMatchJsResult();
637+
});

0 commit comments

Comments
 (0)