TypeScript Compiler API

ts.getLeadingCommentRanges()

Scans leading comments around the supplied source position, returning ranges with kind, pos, end and possible newline metadata. It does not build a complete comment-attachment model. Use the original text and appropriate full-start position; handle undefined. Baseline: TypeScript 5.8.3; run locally with Node.js, not as a ByteMind CodeRunner exercise.

Formal Syntax & Structure

typescript syntaxtypescript
ts.getLeadingCommentRanges(text: string, pos: number): ts.CommentRange[] | undefined

Parameters & Attributes

NameTypeDescription
textstringOriginal source text.
posnumberUTF-16 starting position for comment scanning.

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 parse(text) {  return ts.createSourceFile("input.ts", text, ts.ScriptTarget.ES2022, true, ts.ScriptKind.TS);}const text="// header\nconst x = 1;";const f=parse(text), ranges=ts.getLeadingCommentRanges(text,f.statements[0].getFullStart());assert.equal(ranges.length,1); assert.equal(text.slice(ranges[0].pos,ranges[0].end),"// header");assert.equal(ts.getLeadingCommentRanges("const x=1;",0),undefined); console.log("header found; absent comments return undefined");
// Run: node example.cjs// Expected stdout: header found; absent comments return undefined
TypeScript Reference