Lab 04: TypeScript Compiler API
Step 1: Environment Setup
docker run -it --rm node:20-alpine sh
npm install -g typescript
mkdir lab04 && cd lab04
npm init -y
npm install typescript ts-morphStep 2: Creating a TypeScript Program
// explore-ast.js
const ts = require('typescript');
const fs = require('fs');
// Write a sample TS file to analyze
const sampleCode = `
function greet(name: string): string {
return "Hello, " + name;
}
async function fetchUser(id: number): Promise<string> {
return "user-" + id;
}
const arrowFn = (x: number, y: number): number => x + y;
class UserService {
constructor(private name: string) {}
getUser(): string { return this.name; }
}
`;
fs.writeFileSync('sample.ts', sampleCode);
// Create compiler host and program
const program = ts.createProgram(['sample.ts'], {
target: ts.ScriptTarget.ES2020,
module: ts.ModuleKind.CommonJS,
strict: true,
});
const sourceFile = program.getSourceFile('sample.ts');
console.log('Source file:', sourceFile?.fileName);
console.log('Language version:', sourceFile?.languageVersion);
console.log('Statements count:', sourceFile?.statements.length);Step 3: Understanding SyntaxKind
Step 4: AST Traversal with forEachChild
Step 5: Finding All Function Declarations
Step 6: Type Checking with the Type Checker
Step 7: Simpler Access with ts-morph
Step 8: Capstone — Code Analysis Tool
Summary
Concept
API
Use Case
Last updated
