TypeScript Compiler API

ts.getTrailingCommentRanges()

Scans trailing comments from a source position such as a statement end. Comments on the following line can belong to leading trivia instead. Slice the original text using the returned range; the API does not define a universal ownership model. Baseline: TypeScript 5.8.3; run locally with Node.js, not as a ByteMind CodeRunner exercise.

Formal Syntax & Structure

typescript syntaxtypescript
ts.getTrailingCommentRanges(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="const x=1; // end\n// next\nconst y=2;"; const f=parse(text);const ranges=ts.getTrailingCommentRanges(text,f.statements[0].end);assert.equal(ranges.length,1); assert.equal(text.slice(ranges[0].pos,ranges[0].end),"// end");assert.equal(ts.getTrailingCommentRanges(text,f.statements[1].end),undefined); console.log("same-line trailing comment only");
// Run: node example.cjs// Expected stdout: same-line trailing comment only
TypeScript Reference