TypeScript: get syntax tree

The TypeScript parser doesn’t directly produce a tree like that, but you can still use its object model to do all sorts of things. We use it in some tools to do syntax transforms for testing purposes, for example. Here’s a snippet that you can use to print the syntax tree:

import ts from "typescript";
 
const code = "enum { x = 1 }";
const sc = ts.createSourceFile("x.ts", code, ts.ScriptTarget.Latest, true);

let indent = 0;
function print(node: ts.Node) {
    console.log(new Array(indent + 1).join(" ") + ts.SyntaxKind[node.kind]);
    indent++;
    ts.forEachChild(node, print);
    indent--;
}
 
print(sc);

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)