This is the playground for a blog post about source code metaprogramming with TypeScript.
I take the following data as input via JSON:
[
{
"name": "A",
"type": "boolean"
},
{
"name": "B",
"type": "number"
},
{
"name": "C",
"type": "string"
}
]...and generate the following TypeScript file in three different ways:
interface SomeInterfaceA { discriminator: "A"; type: boolean; } interface SomeInterfaceB { discriminator: "B"; type: number; } interface SomeInterfaceC { discriminator: "C"; type: string; } export type SomeInterface = SomeInterfaceA | SomeInterfaceB | SomeInterfaceC;
The methods to output a TypeScript file include source code generation via:
Make sure you have the following tools installed and available in the $PATH environment variable:
- node - any recent version (
>=14.17) should do, or you can find the exact version in the .tool-versions file for asdf-vm - npm - that one usually ships with
node
Install all dependencies with:
$ npm ci
Either build the project and inspect the output files in ./dist:
$ npm run build
...or execute the generate:*-scripts one-by-one to inspect their output in the console:
# Template literals
$ npm run -s generate:1# A template engine
$ npm run -s generate:2# A writer library
$ npm run -s generate:3# The TypeScript compiler API
$ npm run -s generate:4Have fun!