The TypeScript compiler API lets you work with TypeScript code inside your programs. It helps you read, check, and change TypeScript code automatically.
TypeScript compiler API basics
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.
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);
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]); });
This program reads a simple TypeScript code string, counts how many statements it has, and prints the type of each statement.
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]); });
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.
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.
Practice
What is the primary purpose of the TypeScript compiler API?
SourceFile is a key part of it. What does it help you do?
Solution
Step 1: Understand the role of the compiler API
The TypeScript compiler API is designed to let programs read and change TypeScript code, not to run it or build UI.Step 2: Identify what
SourceFilerepresentsSourceFileis an object representing the code text, allowing exploration and modification.Final Answer:
Read and modify TypeScript code programmatically -> Option BQuick Check:
Compiler API = Code reading and modification [OK]
- Thinking it runs TypeScript code directly
- Confusing it with UI libraries
- Assuming it manually converts code without automation
Which of the following is the correct way to create a SourceFile using the TypeScript compiler API?
const sourceFile = ts.createSourceFile(____);
Solution
Step 1: Recall the
The method requires filename, source text, and script target in that order.createSourceFilesignatureStep 2: Match the correct argument order
('file.ts', codeText, ts.ScriptTarget.Latest) correctly uses ('file.ts', codeText, ts.ScriptTarget.Latest).Final Answer:
('file.ts', codeText, ts.ScriptTarget.Latest) -> Option DQuick Check:
Filename, text, target order = A [OK]
- Swapping filename and code text
- Omitting the script target argument
- Passing arguments in wrong order
Given this code snippet using the TypeScript compiler API:
const sourceFile = ts.createSourceFile('test.ts', 'let x = 5;', ts.ScriptTarget.Latest);
const firstStatement = sourceFile.statements[0];
console.log(firstStatement.kind);What will be printed?
Solution
Step 1: Understand what
The first statement issourceFile.statements[0]islet x = 5;, which is a variable declaration statement.Step 2: Identify the kind of this statement
Its kind isSyntaxKind.VariableStatement, a numeric enum value representing variable statements.Final Answer:
SyntaxKind.VariableStatement -> Option AQuick Check:
First statement kind = VariableStatement [OK]
- Expecting the value 5 to be printed
- Confusing statement kind with identifier kind
- Assuming undefined because of missing imports
Consider this code snippet:
const sourceFile = ts.createSourceFile('file.ts', 'const a = 10;', ts.ScriptTarget.Latest);
const firstStatement = sourceFile.statements[0];
console.log(firstStatement.name.text);What is the error in this code?
Solution
Step 1: Check the type of
firstStatementfirstStatementis a VariableStatement node, which does not have a directnameproperty.Step 2: Understand how to access variable name
The variable name is insidefirstStatement.declarationList.declarations[0].name, not directly onfirstStatement.Final Answer:
firstStatementhas no propertyname-> Option AQuick Check:
VariableStatement lacks direct name property [OK]
- Accessing name directly on VariableStatement
- Assuming sourceFile creation is wrong
- Confusing property names on nodes
You want to write a function using the TypeScript compiler API that extracts all variable names from a given source code string. Which approach is best?
- Create a
SourceFilefrom the code string. - Traverse its statements and declarations.
- Collect names from variable declarations.
Which code snippet correctly starts this process?
function getVariableNames(code: string): string[] {
const sourceFile = ts.createSourceFile('temp.ts', code, ts.ScriptTarget.Latest);
const names: string[] = [];
sourceFile.statements.forEach(statement => {
if (ts.isVariableStatement(statement)) {
statement.declarationList.declarations.forEach(decl => {
if (ts.isIdentifier(decl.name)) {
names.push(decl.name.text);
}
});
}
});
return names;
}Solution
Step 1: Verify SourceFile creation
The code correctly creates aSourceFilefrom the input string.Step 2: Check traversal and extraction logic
It loops over statements, filters variable statements, then loops declarations to extract identifier names properly.Final Answer:
Correctly traverses variable declarations and extracts names -> Option CQuick Check:
Traversal and extraction logic is correct [OK]
- Not creating SourceFile before traversal
- Trying to loop on non-iterable objects
- Pushing nodes instead of text names
Ready to prove it?
Pass the test and this pattern moves unknown
