Kostiantyn Ko
Kostiantyn Ko

Reputation: 2743

Language Services: find Node at position

I'm using Typescript Language Services.

I need to find a ts.Node having just a ts.SourceFile instance and an absolute position (number) of interest as input parameters.

Moreover, I need to cater cases when the token of interest is an else keyword for example, or an opening brace {, or located inside an if condition.

Does anyone know if such a function already exists in the Language Services?

UPD: I managed to find function getTouchingToken (that is presumably does what I need) somewhere in Typescript source code, but I don't see it being exported. Any clues how to reuse it?

Upvotes: 2

Views: 634

Answers (2)

felixfbecker
felixfbecker

Reputation: 2363

You can use tsutils which includes getTokenAtPosition.

This is better than relying on internal TypeScript API that might break any time.

Upvotes: 1

basarat
basarat

Reputation: 276383

I managed to find function getTouchingToken (that is presumably does what I need) somewhere in Typescript source code, but I don't see it being exported. Any clues how to reuse it

I use ts.getTokenAtPosition e.g. to provide the quickfix feature in alm tools for TypeScript 🌹

enter image description here

Upvotes: 1

Related Questions