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?
import ts from 'typescript'; const source = ts.createSourceFile('test.ts', 'const x = 42;', ts.ScriptTarget.Latest, true); console.log(source.text);
Think about what source.text represents in a source file object.
The createSourceFile function creates a source file object that contains the original source code text. Accessing source.text returns the exact string passed in, which is const x = 42;.
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?
Think about which method handles multiple files and type checking.
ts.createProgram creates a program that includes multiple source files and provides type checking and semantic analysis. createSourceFile is for single files, transpileModule is for quick transpilation, and createPrinter is for printing AST nodes.
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?
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);
Check what printNode accepts as arguments and what SourceFile is.
printNode can print any node, including the root SourceFile. So printing the source file node outputs the original source code text. No error occurs.
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?
Check the parameters of createSourceFile in the TypeScript compiler API.
The fourth parameter of createSourceFile is a boolean indicating whether to set the source file as 'strict'. Passing true enables strict mode. Options objects or named parameters are not accepted here.
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?
Each file has one type error. Think about how many errors the compiler reports.
Both files have one type mismatch error each. The compiler reports one diagnostic per error, so total diagnostics are 2.