Printing TypeScript code from AST

This wiki section of TypeScript github project covers how to print an AST (Abstract Syntax Tree) node, but it does not cover how to update and print an entire file (at the time of writing this post).

After a lot of trial and error, I came up with the following. I don’t know whether its the right way to do it but it works:

import ts from 'typescript';

// Create a Printer
const printer = ts.createPrinter({
    newLine: ts.NewLineKind.LineFeed,
    removeComments: false,
    omitTrailingSemicolon: true

// Create a source file
const sourceFile = ts.createSourceFile(
    /*setParentNodes*/ false,

const myASTNode_1 = /* Your AST */;
const myASTNode_2 = /* Your AST */;
const myASTNode_3 = /* Your AST */;
// etc

// Update the source file statements
sourceFile.statements = ts.createNodeArray(
    [ myASTNode_1, myASTNode_2, myASTNode_3, .... ]

// Print the new code

So first we create a ts.Printer object and an empty ts.SourceFile. The code in a SourceFile is located in the statements key which is of type ts.NodeArray. Hence, we use the ts.createNodeArray function to generate ts.NodeArray and replace the statements.

I’ve created a small example here. You can clone it and try for yourselves.

git clone ts-ast
cd ts-ast
yarn install # or npm install
yarn start # or npm start

It should look something like this: