ts-morph for TypeScript: Complete Guide with Examples

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Introduction to ts-morph: What It Is and Why You Need It

\n\n

ts-morph is a powerful library for programmatic work with the TypeScript Abstract Syntax Tree (AST). It provides a convenient and intuitive API for analyzing, modifying, and generating TypeScript code. Unlike directly using the TypeScript Compiler API, ts-morph offers a higher-level interface that significantly simplifies many routine tasks.

\n\n

Why do you need this library? Imagine you need to:

\n
    \n
  • Refactor code: Automatically rename all occurrences of a function, change a method signature, or move a class to another file.
  • \n
  • Static analysis: Find all unused variables, check compliance with corporate coding standards, or collect metadata about the project structure.
  • \n
  • Code generation: Create types based on a JSON schema, generate CRUD operations for a database, or automatically add documentation.
  • \n
  • Build developer tools: Write a linter plugin, a custom documentation generator, or a code migration utility.
  • \n
\n\n

ts-morph abstracts the complexity of the TypeScript Compiler API by providing an object-oriented approach. You work with projects, files, classes, functions, and other code elements as regular objects, rather than low-level AST nodes.

\n\n

Installing ts-morph

\n\n

The library is installed via npm or yarn. It is available as a Node.js package.

\n\n
npm install ts-morph
\n\n

or, if you use yarn:

\n\n
yarn add ts-morph
\n\n

After installation, you can import the library into your project:

\n\n
import { Project } from 'ts-morph';
\n\n

ts-morph requires TypeScript (specified as a peer dependency). Make sure TypeScript is installed in your project:

\n\n
npm install typescript
\n\n

Quick Start with a Code Example

\n\n

Let's write a simple script that creates a new TypeScript file, adds a function to it, and then outputs the generated code.

\n\n
import { Project, SyntaxKind } from 'ts-morph';\n\n// Create a new project\nconst project = new Project({\n    useInMemoryFileSystem: true, // Work in memory, without saving to disk\n});\n\n// Create a new file\nconst sourceFile = project.createSourceFile('example.ts', '');\n\n// Add a function\nconst functionDeclaration = sourceFile.addFunction({\n    name: 'greet',\n    parameters: [{ name: 'name', type: 'string' }],\n    returnType: 'string',\n    statements: [\n        `return \\`Hello, \\${name}!\\`;`,\n    ],\n});\n\n// Add a JSDoc comment\nfunctionDeclaration.addJsDoc({\n    description: 'Greets the user',\n    tags: [{ tagName: 'param', text: 'name - The user\\'s name' }],\n});\n\n// Output the generated code\nconsole.log(sourceFile.getText());\n
\n\n

Script execution result:

\n\n
/**\n * Greets the user\n * @param name - The user's name\n */\nfunction greet(name: string): string {\n    return `Hello, ${name}!`;\n}\n
\n\n

As you can see, we programmatically created a full function with JSDoc documentation. This is just a small part of ts-morph's capabilities.

\n\n

Key Methods and Functions of ts-morph

\n\n

Let's look at 10 key library methods with detailed descriptions and examples.

\n\n

1. Project.createSourceFile()

\n

What it does: Creates a new TypeScript source file in the project. The file can be empty or contain initial code.

\n

Parameters:

\n
    \n
  • filePath: string — path to the file (relative to the project root).
  • \n
  • sourceText?: string — initial file content (optional).

Recommendations