Bird
Raised Fist0
Typescriptprogramming~20 mins

TypeScript compiler API basics - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
TypeScript Compiler API Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this TypeScript compiler API code?

Consider the following TypeScript code that uses the compiler API to create a source file and print its text.

import ts from 'typescript';

const source = ts.createSourceFile('test.ts', 'const x = 42;', ts.ScriptTarget.Latest, true);
console.log(source.text);

What will be printed to the console?

Typescript
import ts from 'typescript';

const source = ts.createSourceFile('test.ts', 'const x = 42;', ts.ScriptTarget.Latest, true);
console.log(source.text);
AAn empty string
BSyntaxError
Cconst x = 42;
Dundefined
Attempts:
2 left
💡 Hint

Think about what source.text represents in a source file object.

🧠 Conceptual
intermediate
1:30remaining
Which TypeScript compiler API method creates a program from source files?

You want to analyze multiple TypeScript files together. Which method from the compiler API should you use to create a program that represents all these files?

Ats.transpileModule
Bts.createSourceFile
Cts.createPrinter
Dts.createProgram
Attempts:
2 left
💡 Hint

Think about which method handles multiple files and type checking.

🔧 Debug
advanced
2:30remaining
What error does this TypeScript compiler API code produce?

Examine this code snippet:

import ts from 'typescript';

const source = ts.createSourceFile('test.ts', 'let a = 1;', ts.ScriptTarget.Latest, true);
const printer = ts.createPrinter();

const result = printer.printNode(ts.EmitHint.Unspecified, source, source);
console.log(result);

What error or output will this code produce?

Typescript
import ts from 'typescript';

const source = ts.createSourceFile('test.ts', 'let a = 1;', ts.ScriptTarget.Latest, true);
const printer = ts.createPrinter();

const result = printer.printNode(ts.EmitHint.Unspecified, source, source);
console.log(result);
ATypeError: printNode expects a Statement node, not SourceFile
BPrints the entire source code: 'let a = 1;'
CSyntaxError: Argument of type 'SourceFile' is not assignable to parameter of type 'Node'
DPrints an empty string
Attempts:
2 left
💡 Hint

Check what printNode accepts as arguments and what SourceFile is.

📝 Syntax
advanced
2:00remaining
Which option correctly creates a TypeScript source file with strict mode enabled?

You want to create a source file with the text "let y = 10;" and specify the script target as ES2020 with strict mode enabled. Which code snippet is correct?

Ats.createSourceFile('file.ts', 'let y = 10;', ts.ScriptTarget.ES2020, true);
Bts.createSourceFile('file.ts', 'let y = 10;', ts.ScriptTarget.ES2020, strict=true);
Cts.createSourceFile('file.ts', 'let y = 10;', ts.ScriptTarget.ES2020, {strict: true});
Dts.createSourceFile('file.ts', 'let y = 10;', ts.ScriptTarget.ES2020);
Attempts:
2 left
💡 Hint

Check the parameters of createSourceFile in the TypeScript compiler API.

🚀 Application
expert
3:00remaining
How many diagnostics are reported by this TypeScript program?

Given these two TypeScript files:

// file1.ts
const a: number = 'hello';

// file2.ts
const b: string = 123;

And this code to create a program and get diagnostics:

import ts from 'typescript';

const program = ts.createProgram(['file1.ts', 'file2.ts'], {});
const diagnostics = ts.getPreEmitDiagnostics(program);
console.log(diagnostics.length);

How many diagnostics will be printed?

A2
B0
C1
D4
Attempts:
2 left
💡 Hint

Each file has one type error. Think about how many errors the compiler reports.

Practice

(1/5)
1.

What is the primary purpose of the TypeScript compiler API?

SourceFile is a key part of it. What does it help you do?

easy
A. Run TypeScript code directly in the browser
B. Read and modify TypeScript code programmatically
C. Convert TypeScript to JavaScript manually
D. Create user interfaces with TypeScript

Solution

  1. 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.
  2. Step 2: Identify what SourceFile represents

    SourceFile is an object representing the code text, allowing exploration and modification.
  3. Final Answer:

    Read and modify TypeScript code programmatically -> Option B
  4. Quick Check:

    Compiler API = Code reading and modification [OK]
Hint: Remember: compiler API reads and changes code, not runs it [OK]
Common Mistakes:
  • Thinking it runs TypeScript code directly
  • Confusing it with UI libraries
  • Assuming it manually converts code without automation
2.

Which of the following is the correct way to create a SourceFile using the TypeScript compiler API?

const sourceFile = ts.createSourceFile(____);
easy
A. (codeText, ts.ScriptTarget.Latest)
B. ('file.ts', codeText)
C. (codeText, 'file.ts', ts.ScriptTarget.Latest)
D. ('file.ts', codeText, ts.ScriptTarget.Latest)

Solution

  1. Step 1: Recall the createSourceFile signature

    The method requires filename, source text, and script target in that order.
  2. Step 2: Match the correct argument order

    ('file.ts', codeText, ts.ScriptTarget.Latest) correctly uses ('file.ts', codeText, ts.ScriptTarget.Latest).
  3. Final Answer:

    ('file.ts', codeText, ts.ScriptTarget.Latest) -> Option D
  4. Quick Check:

    Filename, text, target order = A [OK]
Hint: Filename first, then code text, then script target [OK]
Common Mistakes:
  • Swapping filename and code text
  • Omitting the script target argument
  • Passing arguments in wrong order
3.

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?

medium
A. SyntaxKind.VariableStatement
B. 5
C. SyntaxKind.Identifier
D. undefined

Solution

  1. Step 1: Understand what sourceFile.statements[0] is

    The first statement is let x = 5;, which is a variable declaration statement.
  2. Step 2: Identify the kind of this statement

    Its kind is SyntaxKind.VariableStatement, a numeric enum value representing variable statements.
  3. Final Answer:

    SyntaxKind.VariableStatement -> Option A
  4. Quick Check:

    First statement kind = VariableStatement [OK]
Hint: Statements array holds top-level code pieces; kind shows their type [OK]
Common Mistakes:
  • Expecting the value 5 to be printed
  • Confusing statement kind with identifier kind
  • Assuming undefined because of missing imports
4.

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?

medium
A. firstStatement has no property name
B. sourceFile is not created correctly
C. text is not a valid property
D. No error, code runs fine

Solution

  1. Step 1: Check the type of firstStatement

    firstStatement is a VariableStatement node, which does not have a direct name property.
  2. Step 2: Understand how to access variable name

    The variable name is inside firstStatement.declarationList.declarations[0].name, not directly on firstStatement.
  3. Final Answer:

    firstStatement has no property name -> Option A
  4. Quick Check:

    VariableStatement lacks direct name property [OK]
Hint: Variable names are nested inside declarations, not on statement directly [OK]
Common Mistakes:
  • Accessing name directly on VariableStatement
  • Assuming sourceFile creation is wrong
  • Confusing property names on nodes
5.

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?

  1. Create a SourceFile from the code string.
  2. Traverse its statements and declarations.
  3. 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;
}
hard
A. Incorrect because it uses forEach on a non-iterable
B. Fails because it does not parse the code into a SourceFile
C. Correctly traverses variable declarations and extracts names
D. Wrong because it pushes declaration nodes instead of names

Solution

  1. Step 1: Verify SourceFile creation

    The code correctly creates a SourceFile from the input string.
  2. Step 2: Check traversal and extraction logic

    It loops over statements, filters variable statements, then loops declarations to extract identifier names properly.
  3. Final Answer:

    Correctly traverses variable declarations and extracts names -> Option C
  4. Quick Check:

    Traversal and extraction logic is correct [OK]
Hint: Traverse statements, check variable statements, then extract names [OK]
Common Mistakes:
  • Not creating SourceFile before traversal
  • Trying to loop on non-iterable objects
  • Pushing nodes instead of text names
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard