TypeScript Compiler API

Scanner.lookAhead()

Runs a speculative scanner callback and restores scanner state on normal completion, returning the callback result. This supports peeking without consuming tokens. External side effects are not rolled back; do not assume exception safety. Baseline: TypeScript 5.8.3; run locally with Node.js, not as a ByteMind CodeRunner exercise.

Formal Syntax & Structure

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

Parameters & Attributes

NameTypeDescription
callback() => TSpeculative operation returning a result.

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(); const end=s.getTokenEnd();assert.equal(s.lookAhead(()=>s.scan()),ts.SyntaxKind.PlusToken); assert.equal(s.getToken(),ts.SyntaxKind.Identifier); assert.equal(s.getTokenEnd(),end);assert.equal(s.scan(),ts.SyntaxKind.PlusToken); console.log("peek plus; scan plus again");
// Run: node example.cjs// Expected stdout: peek plus; scan plus again
TypeScript Reference