Search code examples
typescripttransformer-model

How can I create a const assignment in a typescript transformer?


I can create a variable assignment with this code:

ts.createVariableStatement(undefined, 
     [ts.createVariableDeclaration('a', undefined, 
      ts.createStringLiteral('42'))])

/// yields: var a = 42

I cannot however create a const assignment. I am quite sure it should work like so:

ts.createVariableStatement([ts.createModifier(ts.SyntaxKind.ConstKeyword)], 
     [ts.createVariableDeclaration('a', undefined, 
      ts.createStringLiteral('42'))])

but this yields an error:

[!] Error: Unexpected keyword 'var'

an no javascript is emitted due to that error. The error message is very confusing as well.


Solution

  • Try this:

    ts.createVariableStatement(
          [],
          ts.createVariableDeclarationList(
            [
              ts.createVariableDeclaration(
                'a',
                undefined,
                ts.createStringLiteral('42'),
              ),
            ],
            ts.NodeFlags.Const,
          ),
        )
    

    Based on this answer.