# 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.

Source: https://voxgig.com/howto/generate-typescript-with-ts-morph

- Audience: library-maintainer
- Level: intermediate
- Languages: typescript
- Verified: 2026-11-30
- Published: 2026-11-30

## 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](/howto/choose-a-template-engine-for-generated-code).
Pin TypeScript 6 for the `ts.factory` route: TypeScript 7 ships no compiler API in its main entry.

## Approaches compared

| Approach | When it fits | What it costs you | When to pick something else |
| --- | --- | --- | --- |
| [EJS](https://ejs.co/) | The output is mostly fixed text with a few holes the model fills | Every escape is your job, and a broken file appears only when `tsc` reads it | Model values arrive from people you do not review |
| [ts-morph](https://ts-morph.com/manipulation/structures) | You generate declarations and want a parse check before anything is written | Names, types, and bodies are still strings inside the structures, and it adds a dependency | The file is mostly statements, where structures help little |
| [TypeScript compiler API (ts.factory)](https://github.com/microsoft/TypeScript/wiki/Using-the-Compiler-API#creating-and-printing-a-typescript-ast) | You need statements and expressions as nodes too, with no second package | 116 lines of generator against the template's 17, and a printer that drops blank lines | You 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:

```erb title="templates/client.ts.ejs"
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](https://ts-morph.com/manipulation/structures): plain objects with a `kind`, nested
the way the declarations nest. The method list from `gen-morph.mjs`:

```js title="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()`:

```js title="gen-morph.mjs"
// 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`:

```js title="gen-factory.mjs"
  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:

```bash
node generate.mjs
```

```text output
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:

```bash
wc -l templates/client.ts.ejs gen-ejs.mjs gen-morph.mjs gen-factory.mjs
```

```text output
  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](https://prettier.io/docs/api) and diffs each against the EJS output:

```bash
node check.mjs
```

```text output
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](https://prettier.io/docs/rationale#empty-lines) 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:

```bash
node --test generator.test.mjs
```

```text output
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`](https://ts-morph.com/details/functions) and once through `pathExpression`. Then
it hands a structure a property named `x-request-id`:

```bash
node pitfall.mjs
```

```text output
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](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-6-0.html#specifying-command-line-files-when-tsconfigjson-exists-is-now-an-error)
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:

```bash
cat records/typescript-7.txt
```

```text output
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.

## Related how-tos

- [Choose a template engine for generating source code](/howto/choose-a-template-engine-for-generated-code)

- [Format generated code as the last step of generation](/howto/format-generated-code-as-the-last-step)

- [Run a codemod across every generated file with jscodeshift](/howto/jscodeshift-codemod-across-generated-files)

- [Test a project generator without writing files to disk](/howto/test-a-generator-without-writing-to-disk)

- [Update scaffolded projects when the template changes](/howto/update-scaffolded-projects-when-the-template-changes)

## 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.

[^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](https://prettier.io/docs/rationale#empty-lines) states no other rule, so every
other blank line stays where the source had it, which for a printer's output is nowhere.

[^2]: The [TypeScript 7.0 announcement](https://devblogs.microsoft.com/typescript/announcing-typescript-7-0/)
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.