Skip to content

Transformer: hoistVariableDeclaration does not work correctly with class fields聽#44327

Description

Bug Report

The hoisted variables in class fields are not pre-class. This makes all instance of the class shares the same temp variable. TS class transformers should be applied if there are hoist temp variables in the class field initializer position.

馃攷 Search Terms

class fields hoistVariableDeclaration

馃晽 Version & Regression Information

  • Tested on 4.3.2

馃捇 Code

import * as ts from 'typescript'
const code = `class T {
    field = 1
}`

const out = ts.transpileModule(code, {
    compilerOptions: { target: ts.ScriptTarget.ESNext },
    transformers: { before: [transfromer()] },
})
console.log(out.outputText)

function transfromer() {
    return (ctx: ts.TransformationContext) => {
        return (sourceFile: ts.SourceFile) => {
            function visitor(node: ts.Node): ts.Node {
                const parent = node.parent
                if (ts.isPropertyDeclaration(parent) && parent.initializer === node) {
                    const temp = ctx.factory.createTempVariable(ctx.hoistVariableDeclaration, true)
                    return ctx.factory.createImmediatelyInvokedArrowFunction([ctx.factory.createReturnStatement(temp)])
                }
                return ts.visitEachChild(node, visitor, ctx)
            }
            return ts.visitEachChild(sourceFile, visitor, ctx)
        }
    }
}

馃檨 Actual behavior

var _a;
class T {
    field = (() => {
        return _a;
    })();
}

馃檪 Expected behavior

class T {
    constructor() {
        var _a;
        this.field = (() => {
            return _a;
        })();
    }
}

Metadata

Metadata

Labels

Domain: API: TransformsRelates to the public transform APIWorking as IntendedThe behavior described is the intended behavior; this is not a bug

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions