How-to › Model, configure and generate

How to generate TypeScript with ts-morph instead of a template#

Rebuild an EJS template that emits a typed client as ts-morph structures, compare it with ts.factory, and prove every output type-checks and matches after Prettier.

Audience
Library maintainer
Level
intermediate
Topic
Engineer templates and AST transforms
Languages
TypeScript
Verified

Read first: Choose a template engine for generating source code

Your EJS template prints a typed API client, and a model change breaks it in a way no test sees until build time. A path in the model carries a quote, and the generated method gains a second statement that compiles. A field named x-request-id prints unquoted, and tsc rejects a file the generator reported as written.

What you get

You will end up with a ts-morph generator that writes the same client as the template. A check type-checks every output and proves they agree after Prettier. This is for library maintainers who own a template-based generator.

Short answer

Build the file as one ts-morph SourceFileStructure, with interfaces, a class, and methods as structures, and write it with project.saveSync() after a syntax check. Structures stop at declarations, so a method body is still a string; build it from model values quoted by code. Prove it with tsc --noEmit on the output and a diff against the EJS output after both pass through Prettier.

You will need

Node 22 or later and a TypeScript project with a build step. Verified 2026-11-30 against Node 22.23.5, ts-morph 28.0.0, TypeScript 6.0.3, EJS 7.0.2, and Prettier 3.10.1. The page builds on choose a template engine for generating source code. Pin TypeScript 6 for the ts.factory route: TypeScript 7 ships no compiler API in its main entry.

Approaches compared

ApproachWhen it fitsWhat it costs youWhen to pick something else
EJSThe output is mostly fixed text with a few holes the model fillsEvery escape is your job, and a broken file appears only when tsc reads itModel values arrive from people you do not review
ts-morphYou generate declarations and want a parse check before anything is writtenNames, types, and bodies are still strings inside the structures, and it adds a dependencyThe file is mostly statements, where structures help little
TypeScript compiler API (ts.factory)You need statements and expressions as nodes too, with no second package116 lines of generator against the template’s 17, and a printer that drops blank linesYou only emit declarations, where ts-morph structures said the same in 67 lines

The template is the shortest of the three and checks nothing. ts-morph parses what it prints and lets you refuse a broken file, but it takes text for every name and body. ts.factory builds even the return as nodes, at the price of a generator nearly seven times the template’s length.

Start from the template

The EJS template prints each method as a line of text, with the model’s values in <%- %> holes:

export class <%- model.client %> {
  constructor(private readonly transport: Transport) {}
<% for (const op of model.operations) { %>
  <%- op.name %>(<%- [...op.params.map((p) => p + ': string'), ...(op.body ? ['body: ' + op.body] : [])].join(', ') %>): Promise<<%- returnType(op) %>> {
    return request<<%- returnType(op) %>>(this.transport, <%- JSON.stringify(op.method) %>, <%- pathExpression(op) %><%- op.body ? ', body' : '' %>);
  }
<% } -%>
}

model.mjs already does the work a template cannot. It refuses any name that ts.isIdentifierText rejects, a keyword where a name becomes a type, the class, or a parameter, and a name the file already uses, such as Transport. pathExpression quotes each literal part of a path with JSON.stringify. All three generators share it, so they differ only in how they build the text.

Build the same file from structures

ts-morph takes the whole file as a structure: plain objects with a kind, nested the way the declarations nest. The method list from gen-morph.mjs:

          methods: model.operations.map((op) => ({
            name: op.name,
            parameters: [
              ...op.params.map((p) => ({ name: p, type: 'string' })),
              ...(op.body ? [{ name: 'body', type: op.body }] : []),
            ],
            returnType: `Promise<${returnType(op)}>`,
            // Structures stop at declarations, so a body is text. Keep it to one
            // statement whose model values were quoted by model.mjs.
            statements: [
              `return request<${returnType(op)}>(this.transport, ${JSON.stringify(op.method)}, ${pathExpression(op)}${op.body ? ', body' : ''});`,
            ],
          })),

The statements entry is text because it has to be: ts-morph takes a string, a writer function that writes a string, or a structure. Its StatementStructures type lists classes, enums, functions, interfaces, modules, type aliases, imports, exports, and variable statements. It has no structure for a return, an if, or a call.

Before writing, saveChecked asks the compiler for syntax errors in the file ts-morph printed, and only then calls project.saveSync():

// Structures take names and types as strings, so a bad one prints as bad
// TypeScript. Parse the result and refuse to write it.
export function saveChecked(project, file) {
  const errors = project.getProgram().getSyntacticDiagnostics(file)
  if (errors.length > 0) {
    throw new Error(`${file.getBaseName()}: ${errors.length} syntax errors, nothing written`)
  }
  project.saveSync()
}

Build it again from compiler API nodes

gen-factory.mjs builds every part as a node, down to the string literals and the + between path parts, and prints the list with ts.createPrinter:

  const call = f.createCallExpression(f.createIdentifier('request'), [returnTypeNode(op)], [
    f.createPropertyAccessExpression(f.createThis(), 'transport'),
    f.createStringLiteral(op.method),
    pathNode(op),
    ...(op.body ? [f.createIdentifier('body')] : []),
  ])

Generate all three:

node generate.mjs
wrote generated/ejs/client.ts (30 lines)
wrote generated/morph/client.ts (31 lines)
wrote generated/factory/client.ts (24 lines)

The factory output is shorter because the printer puts no blank line between declarations or members. The size of each generator, counted:

wc -l templates/client.ts.ejs gen-ejs.mjs gen-morph.mjs gen-factory.mjs
  17 templates/client.ts.ejs
  16 gen-ejs.mjs
  67 gen-morph.mjs
 116 gen-factory.mjs
 216 total

Check it worked

check.mjs runs tsc --noEmit on each output, then formats all three with the Prettier API and diffs each against the EJS output:

node check.mjs
tsc --noEmit generated/ejs/client.ts: ok
tsc --noEmit generated/morph/client.ts: ok
tsc --noEmit generated/factory/client.ts: ok
ejs vs morph: raw differs, after Prettier identical
ejs vs factory: raw differs, after Prettier 6 lines differ, 6 of them blank

ts-morph indents with four spaces and EJS with two, so the raw files differ. After Prettier, the ts-morph output is byte for byte the EJS output. The factory output still differs by the six blank lines the printer never wrote, because Prettier keeps empty lines the way they were and adds none.1 Run node check.mjs --diff to see them.

The tests pin all of it, and also fail if a committed output drifts from what the generators write. One feeds every TypeScript keyword through all three generators as a field name and a method name, where the loader lets keywords through, and type-checks the result:

node --test generator.test.mjs
1..9
# tests 9
# suites 0
# pass 9
# fail 0
# cancelled 0
# skipped 0
# todo 0
# duration_ms 16526.497469

When it goes wrong

pitfall.mjs feeds ts-morph a path with a quote in it, once interpolated into setBodyText and once through pathExpression. Then it hands a structure a property named x-request-id:

node pitfall.mjs
setBodyText with the path interpolated: 0 syntax errors, 2 statements, contains an assignment: true
setBodyText with pathExpression(): 0 syntax errors, 1 statements, contains an assignment: false
property named x-request-id prints as: "interface Headers {\n    x-request-id: string;\n}\n"
saveChecked: headers.ts: 3 syntax errors, nothing written

The interpolated body parses cleanly and holds an assignment the model smuggled in. A syntax check cannot catch that, so quote every model value in code before it reaches a body. The unquoted name is the opposite case: it prints as broken TypeScript, and only the parse check stops it.

tsc stops with error TS5112 and checks nothing. TypeScript 6 refuses files named on the command line when a tsconfig.json sits in the working directory, as its 6.0 release notes describe. Its search for that file climbs through every parent directory, so a repository’s root config is enough. Pass --ignoreConfig, as check.mjs does, or point tsc -p at a config of the generator’s own.

ts.factory is undefined after an upgrade. TypeScript 7 exposes no API from its main entry:

cat records/typescript-7.txt
typescript 7.0.2
main entry exports: version, versionMajorMinor
ts.factory: undefined
ts.createPrinter: undefined
package exports: ./package.json, ., ./unstable/sync, ./unstable/async, ./unstable/fs, ./unstable/proto, ./unstable/ast, ./unstable/ast/is, ./unstable/ast/factory, ./unstable/ast/utils, ./unstable/ast/scanner, ./unstable/ast/visitor, ./unstable/ast/clone

The package does export an AST factory, under unstable/ast/factory, and this page did not run it. Keep typescript at 6 for the generator, or alias it the way the TypeScript 7 announcement suggests.2

When not to do this

Do not replace a template that emits mostly fixed text. The EJS generator here is 33 lines across two files, and ts-morph bought one thing for the extra code: a parse before the write.

Do not treat a structure as a guarantee of valid output. Names, types, and bodies go in as strings, and the sample’s own loader, not ts-morph, refuses x-request-id.

Do not move to ts.factory for declarations alone. It took 116 lines where ts-morph took 67, and its output needs blank lines put back before Prettier can match a hand-formatted file.

Do not skip Prettier on any of the three. None of the raw outputs matched another.

Last verified

Verified 2026-11-30 against Node 22.23.5, ts-morph 28.0.0, TypeScript 6.0.3, EJS 7.0.2, and Prettier 3.10.1. Every output block is what the command preceding it printed. The TypeScript 7.0.2 record came from record.sh, which installed that release once into a scratch directory. Its unstable entry points were listed, not run.

Footnotes

  1. The rationale page for Prettier gives its reason first. Empty lines turn out to be hard to generate automatically, so Prettier keeps them the way they were in the source. It collapses runs of them to one and removes those at the start and end of a block. The same page states no other rule, so every other blank line stays where the source had it, which for a printer’s output is nowhere. ↩︎ Back to text

  2. The TypeScript 7.0 announcement says the release “does not ship with an API” and expects 7.1 to bring a different one. Meanwhile it publishes @typescript/typescript6, a package whose executable is named tsc6 and which re-exports the 6.0 API, so a project can run both compilers side by side. ↩︎ Back to text

Read this page as markdown · All how-to guides

Generate the client instead of writing it#

Retries, timeouts, pagination and auth are the same problems in every client. Voxgig generates them from your OpenAPI description, in 23 languages, from one model.

Listen to Fireside, the Voxgig podcast

Since 2018, Richard Rodger has talked with developer advocates, event organizers, and the people who build developer-facing companies about the specifics of the work.