TypeScript Compiler API

ts.createScanner()

Creates a mutable lexical scanner over source text. Choose the language target and trivia handling; use the language variant appropriate to the input. Scanning alone is not parsing or type checking: the parser can rescan context-sensitive tokens. The example contrasts trivia retention with skipping. Baseline: TypeScript 5.8.3; run locally with Node.js, not as a ByteMind CodeRunner exercise.

Formal Syntax & Structure

typescript syntaxtypescript
ts.createScanner(languageVersion: ts.ScriptTarget, skipTrivia: boolean, languageVariant?: ts.LanguageVariant, textInitial?: string, onError?: ts.ErrorCallback, start?: number, length?: number): ts.Scanner

Parameters & Attributes

NameTypeDescription
languageVersionts.ScriptTargetLanguage target.
skipTriviabooleanSkip whitespace and comments when true.
languageVariantts.LanguageVariantStandard or JSX variant.
textInitialstringInitial source text.
onErrorts.ErrorCallbackLexical error callback.
startnumberInitial UTF-16 offset.
lengthnumberLength of scanning range.

Working Example

Example Snippettypescript
// Use a new empty directory. Install: npm install --save-exact typescript@5.8.3// File: example.cjs (omit this label)const ts = require("typescript");const assert = require("node:assert/strict");function scanner(text, skipTrivia = true) {  return ts.createScanner(ts.ScriptTarget.ES2022, skipTrivia, ts.LanguageVariant.Standard, text);}const a = scanner("// note\nlet x", true), b = scanner("// note\nlet x", false);assert.equal(a.scan(), ts.SyntaxKind.LetKeyword);assert.equal(b.scan(), ts.SyntaxKind.SingleLineCommentTrivia);console.log("trivia skipped or retained");
// Run: node example.cjs// Expected stdout: trivia skipped or retained
TypeScript Reference