Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

whilenot-dev/typescript-source-code-generation

Repository files navigation

TypeScript source code generation

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:

  1. Template literals
  2. A template engine
  3. A writer library
  4. The TypeScript compiler API

Prerequisites

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

Setup

Install all dependencies with:

$ npm ci

Usage

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:4

Have fun!

About

Playground for a blog post about TypeScript source code generation

Topics

Resources

License

Stars

Watchers

Forks

AltStyle によって変換されたページ (->オリジナル) /