TypeScript Compiler API

Scanner.tryScan()

Executes speculative scanning and commits the scanner state when the callback returns a truthy result. On a falsy result it restores the prior scanner state. External effects are not reverted; use a deliberate truthy success value rather than relying on arbitrary token numbers. Baseline: TypeScript 5.8.3; run locally with Node.js, not as a ByteMind CodeRunner exercise.

Formal Syntax & Structure

typescript syntaxtypescript
scanner.tryScan<T>(callback: () => T): T

Parameters & Attributes

NameTypeDescription
callback() => TSpeculative operation; truthiness controls commit.

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 s=scanner("a + b"); s.scan();assert.equal(s.tryScan(()=>{s.scan(); return false;}),false); assert.equal(s.getTokenText(),"a");assert.equal(s.tryScan(()=>s.scan()===ts.SyntaxKind.PlusToken),true); assert.equal(s.getToken(),ts.SyntaxKind.PlusToken);assert.equal(s.scan(),ts.SyntaxKind.Identifier); assert.equal(s.getTokenText(),"b");console.log("rollback false; commit true");
// Run: node example.cjs// Expected stdout: rollback false; commit true
TypeScript Reference