API Reference

ts-morph

TypeScript compiler API wrapper that navigates and manipulates source files through fluent objects.

Official Documentation ↗
CompatibilityThis documentation covers version v23. Check the official docs for the latest API surface.

Installation

npmnpm install ts-morph
pnpmpnpm add ts-morph

Methods

TypeScript compiler API wrapper that navigates and manipulates source files through fluent objects.

Overview

ts-morph wraps the TypeScript compiler in an object model: a Project loads files with the real tsconfig, SourceFile exposes declarations through typed methods, and manipulation methods insert code with correct formatting.

It powers codemods, code generators, and static analyzers without regex surgery. Everything is held in memory until save, so multi-step transformations compose safely, and the underlying compiler guarantees the output is syntactically valid.

Core Methods

The most frequently used entry points, with signatures and runnable examples:

  • new Project — Creates the workspace holding files and shared compiler options.
  • getSourceFile / navigations — Fetches a file and walks its declarations through typed accessor methods.
  • addMethod / addImport — Inserts declarations with printer-correct formatting that matches project style.
  • save / saveSync — Writes in-memory edits back to disk, applying the printer to the whole tree.

Usage Notes

  • Load through tsConfigFilePath so path aliases and compiler options match the app.
  • Prefer structure-based manipulation, addMethod with statements, over string splicing.
  • Save once after all edits, then run the type checker in the same pipeline.

Common Pitfalls

  • Manipulating files without saving loses the entire edit on process exit.
  • Large projects load slowly; skipAddingFilesFromTsConfig plus targeted addSourceFileAtPath keeps memory sane.
  • Reformatting expectations belong to prettier, not the compiler printer.

FAQ

Why use ts-morph instead of the raw compiler API?
The compiler API is verbose and position-based; ts-morph wraps it in fluent nodes with structures, formatting, and navigation. The same manipulations take a fraction of the code and stay readable.
How does it handle formatting?
ts-morph uses the TypeScript printer and respects compiler options; reprints preserve indentation and style. For whole-file reformatting, hand off to your formatter, prettier, as a separate step after save.
Is manipulation safe for codemods?
Yes, with discipline: load the project, mutate structures, then save once. Avoid mixing raw string splices with node edits, and run type checks after the codemod to prove the output still compiles.