typescripttypescript-compiler-api

Typescrypt Compiler Api create as const assertion


I want to create an array from string literals with the Typescript Compiler Api that looks like this:

const myArray = ["entry1", "entry2"] as const

For the array itself Im using:

const myArray = ts.factory.createVariableDeclarationList(
    [
      ts.factory.createVariableDeclaration(
        'myArray ',
        undefined,
        undefined,
        ts.factory.createArrayLiteralExpression([
          ts.factory.createStringLiteral('entry1'), 
          ts.factory.createStringLiteral('entry2')
        ])
      )
    ],
    ts.NodeFlags.Const
  )

Which results in const myArray = ["entry1", "entry2"]

How do I add the as const at the end.


Solution

  • Create an as expression with a type reference to const:

    const myArray = ts.factory.createVariableDeclarationList(
      [
        ts.factory.createVariableDeclaration(
          'myArray',
          undefined,
          undefined,
          ts.factory.createAsExpression(
            ts.factory.createArrayLiteralExpression([
              ts.factory.createStringLiteral('entry1'),
              ts.factory.createStringLiteral('entry2'),
            ]),
            ts.factory.createTypeReferenceNode('const')
          )
        ),
      ],
      ts.NodeFlags.Const
    );