0
0
Typescriptprogramming~30 mins

TypeScript compiler API basics - Mini Project: Build & Apply

Choose your learning style9 modes available
TypeScript Compiler API Basics
📖 Scenario: You are building a simple tool that reads TypeScript code and extracts the names of all functions declared in it. This is useful for understanding code structure quickly.
🎯 Goal: Create a TypeScript program that uses the TypeScript compiler API to parse a given TypeScript source code string and list all function names declared in it.
📋 What You'll Learn
Create a variable holding TypeScript source code as a string
Set up a TypeScript compiler API source file from the string
Use a function to visit nodes and find function declarations
Print the list of function names found
💡 Why This Matters
🌍 Real World
Developers use the TypeScript compiler API to build tools that analyze or transform TypeScript code automatically.
💼 Career
Understanding the compiler API is useful for roles in tooling, code analysis, and advanced TypeScript development.
Progress0 / 4 steps
1
Create TypeScript source code string
Create a variable called sourceCode and set it to the string containing these exact lines of TypeScript code with line breaks:
function greet() { console.log('Hello'); }
function add(a: number, b: number) { return a + b; }
Typescript
Need a hint?

Use backticks ` to create a multi-line string in TypeScript.

2
Create a SourceFile using TypeScript compiler API
Import ts from 'typescript' and create a variable called sourceFile by calling ts.createSourceFile with these exact arguments:
- 'temp.ts' as fileName
- sourceCode as sourceText
- ts.ScriptTarget.Latest as languageVersion
- true as setParentNodes
Typescript
Need a hint?

Use ts.createSourceFile to parse the code string into a source file object.

3
Write a function to find function declarations
Create a function called findFunctionNames that takes node of type ts.Node and an array names of strings. Inside it, use ts.forEachChild to visit each child node. If a child node is a function declaration (ts.isFunctionDeclaration(child)) and has a name, push the name text to names. Recursively call findFunctionNames on each child node.
Typescript
Need a hint?

Use recursion and ts.forEachChild to visit all nodes and collect function names.

4
Collect and print function names
Create an empty array called functionNames. Call findFunctionNames with sourceFile and functionNames. Then print functionNames using console.log.
Typescript
Need a hint?

Remember to call the function and then print the array.