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
6 changes: 5 additions & 1 deletion src/transformation/visitors/class/members/constructor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import * as ts from "typescript";
import * as lua from "../../../../LuaAST";
import { TransformationContext } from "../../../context";
import { createSelfIdentifier } from "../../../utils/lua-ast";
import { transformInPrecedingStatementScope } from "../../../utils/preceding-statements";
import { popScope, pushScope, ScopeType } from "../../../utils/scope";
import { transformFunctionBodyContent, transformFunctionBodyHeader, transformParameters } from "../../function";
import { transformIdentifier } from "../../identifier";
Expand Down Expand Up @@ -43,7 +44,9 @@ export function transformConstructorDeclaration(
// Check for field declarations in constructor
const constructorFieldsDeclarations = statement.parameters.filter(p => p.modifiers !== undefined);

const classInstanceFields = transformClassInstanceFields(context, instanceFields);
const [fieldsPrecedingStatements, classInstanceFields] = transformInPrecedingStatementScope(context, () =>
transformClassInstanceFields(context, instanceFields)
);

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

bodyWithFieldInitializers.push(...fieldsPrecedingStatements);
bodyWithFieldInitializers.push(...classInstanceFields);

bodyWithFieldInitializers.push(...body);
Expand Down
12 changes: 12 additions & 0 deletions test/unit/precedingStatements.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -623,3 +623,15 @@ test("else if", () => {
return i;
`.expectToMatchJsResult();
});

// https://github.com/TypeScriptToLua/TypeScriptToLua/issues/1208
test("class member initializers", () => {
util.testFunction`
class MyClass {
myField = false ?? true;
constructor(public foo: number = 0 ?? 5) {}
}
const inst = new MyClass();
return [inst.myField, inst.foo];
`.expectToMatchJsResult();
});