0
0
Typescriptprogramming~10 mins

TypeScript compiler API basics - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to import the TypeScript compiler API.

Typescript
import * as ts from '[1]';
Drag options to blanks, or click blank then click option'
Atypescript
Btsc
Ctypescript-api
Dts
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'tsc' or 'ts' as the package name instead of 'typescript'.
Trying to import from a non-existent package.
2fill in blank
medium

Complete the code to create a TypeScript program from source files.

Typescript
const program = ts.createProgram({ rootNames: ['file.ts'], [1]: {} });
Drag options to blanks, or click blank then click option'
Aconfig
Boptions
Csettings
DcompilerOptions
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'options' or 'config' instead of 'compilerOptions'.
Omitting compiler options entirely.
3fill in blank
hard

Fix the error in the code to get the source file from the program.

Typescript
const sourceFile = program.getSourceFile([1]);
Drag options to blanks, or click blank then click option'
A0
Bundefined
C'file.ts'
Dnull
Attempts:
3 left
💡 Hint
Common Mistakes
Passing a number or null instead of the file name string.
Passing undefined which returns undefined.
4fill in blank
hard

Fill both blanks to create a printer and print the source file.

Typescript
const printer = ts.createPrinter([1]);
const result = printer.printFile([2]);
Drag options to blanks, or click blank then click option'
A{}
BsourceFile
Cnull
D{ removeComments: true }
Attempts:
3 left
💡 Hint
Common Mistakes
Passing null instead of an options object.
Passing a file name string instead of the source file object to printFile.
5fill in blank
hard

Fill all three blanks to create a diagnostic reporter and report errors.

Typescript
const diagnostics = program.getSemanticDiagnostics();
diagnostics.forEach(diagnostic => {
  const message = ts.flattenDiagnosticMessageText(diagnostic.messageText, [1]);
  console.[2](`Error in file: ${diagnostic.file?.fileName} - ${message}`);
  if (diagnostic.start !== undefined) {
    const { line, character } = diagnostic.file!.getLineAndCharacterOfPosition([3]);
    console.log(`At line ${line + 1}, character ${character + 1}`);
  }
});
Drag options to blanks, or click blank then click option'
A2
Berror
Cdiagnostic.start
Dlog
Attempts:
3 left
💡 Hint
Common Mistakes
Using console.log instead of console.error for errors.
Passing wrong arguments to flattenDiagnosticMessageText.
Using diagnostic.file instead of diagnostic.start for position.