Using the TypeScript AST
Updated: 23 July 2024
Generating Typescript using AST’s
Some parsers other that the Typescript one is Esprima, Acorn, these are Javascript Parsers> Other languages also have parsers as well as tools called
Parser Generators
that enable you to generate a parser for a given language or usecase
Before getting started, you should first install the typescript
package into your project with:
Using the typescript compiler you are able to parse TS into an AST as well as build code using the TS AST
You can also generate the
ts.
code using the Typescript to AST Converter
Generate Types
To generate a type like above using the TS compiler you can use the following:
We can then use the generated type to build a more complex type:
Next, we’ll creata a NodeArray
our of the two type declarations we want in our file like so:
Printing to Code
We can then print the two types out as Typescript code with the following:
The above sourcefile is a way for us to store some basic settings for the file we’re going to be saving our file content into, we’ve got the name placeholder.ts
in the above case but this doesn’t really output the file we’re going to be outputing
Next, we can create a Printer
instance and use it to generate our output file:
Lastly, we can print the outputFile
using fs
:
Which will output the following:
References
In addition to using the AST Direcly, some libraries that are also handy for working with the Typescript AST are: