Skip to main content

Introduction

The TypeScript Compiler API provides programmatic access to the TypeScript compiler, allowing you to analyze, transform, and compile TypeScript code in your applications. This API is used internally by the TypeScript compiler itself and is available for external use.

Key Components

The Compiler API consists of several core components:

Program

The Program is the central interface that represents a compilation unit. It manages a collection of source files and compiler options.

TypeChecker

The TypeChecker provides semantic analysis capabilities, allowing you to query type information, resolve symbols, and perform type-related operations.

Scanner

The Scanner performs lexical analysis, breaking source text into tokens.

Parser

The Parser performs syntactic analysis, converting tokens into an Abstract Syntax Tree (AST).

Basic Usage

Here’s a complete example of using the Compiler API to create a program and analyze TypeScript code:

Creating a Program

There are two ways to create a program:

Using CreateProgramOptions

Using Individual Parameters

Working with Source Files

Source files are created using the createSourceFile function:

Compiler Host

The CompilerHost interface abstracts file system operations. You can provide a custom host to control how files are read and written:

Next Steps

Program API

Learn about the Program interface and its methods

TypeChecker API

Explore type checking and semantic analysis

Scanner API

Understand lexical analysis and tokenization

Parser API

Work with AST creation and parsing

Resources