From af8324a98634ec81188a441d3b47bf88667f418b Mon Sep 17 00:00:00 2001 From: Perryvw Date: Thu, 13 Jan 2022 20:36:24 +0100 Subject: [PATCH] Put preceding statements for class fields in the constructor instead of file scope --- .../visitors/class/members/constructor.ts | 6 +++++- test/unit/precedingStatements.spec.ts | 12 ++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/src/transformation/visitors/class/members/constructor.ts b/src/transformation/visitors/class/members/constructor.ts index 11766d2a8..3dfd6a26d 100644 --- a/src/transformation/visitors/class/members/constructor.ts +++ b/src/transformation/visitors/class/members/constructor.ts @@ -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"; @@ -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 @@ -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); diff --git a/test/unit/precedingStatements.spec.ts b/test/unit/precedingStatements.spec.ts index 6ff6b4706..79769e519 100644 --- a/test/unit/precedingStatements.spec.ts +++ b/test/unit/precedingStatements.spec.ts @@ -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(); +});