The TypeScript compiler API lets you work with TypeScript code inside your programs. It helps you read, check, and change TypeScript code automatically.
0
0
TypeScript compiler API basics
Introduction
You want to build a tool that checks your TypeScript code for errors.
You want to create a program that changes TypeScript code automatically.
You want to analyze TypeScript code to understand how it works.
You want to make a custom code formatter or linter for TypeScript.
You want to convert TypeScript code into another format or language.
Syntax
Typescript
import * as ts from 'typescript'; const sourceCode = `let x: number = 5;`; const sourceFile = ts.createSourceFile('example.ts', sourceCode, ts.ScriptTarget.Latest); // Use the sourceFile object to read or change the code
Use ts.createSourceFile to turn code text into a structure you can work with.
The sourceFile object holds the code in a way the API understands.
Examples
This example creates a source file and prints how many statements it has.
Typescript
import * as ts from 'typescript'; const code = `const a = 10;`; const file = ts.createSourceFile('file.ts', code, ts.ScriptTarget.Latest); console.log(file.statements.length);
This example prints the type of each statement in the code.
Typescript
import * as ts from 'typescript'; const code = `function greet() { console.log('Hi'); }`; const file = ts.createSourceFile('greet.ts', code, ts.ScriptTarget.Latest); file.statements.forEach(stmt => { console.log(ts.SyntaxKind[stmt.kind]); });
Sample Program
This program reads a simple TypeScript code string, counts how many statements it has, and prints the type of each statement.
Typescript
import * as ts from 'typescript'; const code = `let message: string = 'Hello, world!';`; const sourceFile = ts.createSourceFile('hello.ts', code, ts.ScriptTarget.Latest); console.log('Number of statements:', sourceFile.statements.length); sourceFile.statements.forEach(statement => { console.log('Statement kind:', ts.SyntaxKind[statement.kind]); });
OutputSuccess
Important Notes
The TypeScript compiler API uses SyntaxKind to name parts of the code.
Working with the API can be tricky at first, but it lets you do powerful things with code.
Summary
The TypeScript compiler API helps you read and change TypeScript code inside programs.
You start by creating a SourceFile from code text.
You can then explore and work with the code using the API's tools.