Summary - Compiler API
- TypeScript course
- Expert
- Lesson 4/35
- 4 min
Write a simple code analysis tool with the Compiler API.
Compiler API summary
Three pieces together give you full code analysis with the Compiler API: ts.createProgram sets up the compilation, program.getTypeChecker() provides symbol and type resolution, and ts.forEachChild walks the AST nodes. For in-memory sources you supply a CompilerHost; nothing is written to disk.
const program = ts.createProgram(files, opts, host);
const checker = program.getTypeChecker();
function visit(node: ts.Node) {
// resolve types with checker; descend with forEachChild
ts.forEachChild(node, visit);
}
visit(sourceFile);Practice List functions
Create a source file with two functions: function topla(a: number, b: number): number { return a + b; } and function yaz(metin: string) { console.log(metin); }. Use ts.createSourceFile to build the SourceFile. Write a visit function; find each function with ts.isFunctionDeclaration and print name: parameterCount. Walk the tree with ts.forEachChild.
Starter code
import * as ts from "typescript";
// İki fonksiyonlu kaynak:
// function topla(a: number, b: number): number { return a + b; }
// function yaz(metin: string) { console.log(metin); }
// SourceFile oluştur
// visit fonksiyonu yaz: FunctionDeclaration düğümlerini bul
// Her fonksiyon için ad: parametreSayisi yazdır
// forEachChild ile ağacı gez
// kodunu buraya yazSample solution
import ts from "typescript";
const sourceText = "function topla(a: number, b: number): number { return a + b; }\nfunction yaz(metin: string) { console.log(metin); }";
const sf = ts.createSourceFile("app.ts", sourceText, ts.ScriptTarget.Latest, true);
function visit(node: ts.Node) {
if (ts.isFunctionDeclaration(node) && node.name) {
console.log(`${node.name.text}: ${node.parameters.length}`);
}
ts.forEachChild(node, visit);
}
visit(sf);Expected output
topla: 2 yaz: 1
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which trio comes together for full code analysis?
- getTypeChecker + writeFile + readFile
- getSourceFile + getText + console.log
- createProgram + TypeChecker + forEachChild Correct answer
- createSourceFile + JSON.stringify + writeFile
Explanation: createProgram sets up the compilation, the TypeChecker resolves meaning and forEachChild walks the syntax tree; together they give full analysis.
2 TypeChecker call
const program = ts.createProgram([fileName], { noLib: true }, host);
const checker = program.____;
const program = ts.createProgram([fileName], { noLib: true }, host);
const checker = program.getTypeChecker();
Explanation: program.getTypeChecker() returns the TypeChecker; getChecker, createChecker and typeChecker do not exist on Program.
3 Compiler API summary
| Term | Meaning |
|---|---|
createProgram |
Compilation object |
getSourceFiles |
Source files |
getTypeChecker |
Semantic resolver |
forEachChild |
AST traversal |