What is the best way to retrieve all references to a specific node by utilizing the TypeScript API?

Given a variable declaration like let i = 0 or const j = getSomething();, the task is to determine if the variable is an integer, float, or another type (not just numeric vs non-numeric). The approach involves identifying all instances where the value is assigned, determining their types recursively, and checking if any of them are set to something other than an integer.

The available resources include a ts.TypeChecker and ts.Program. Daniel Rosenwasser's tweets suggest that the checker API is the way to proceed, but it can be challenging to identify the specific APIs to utilize.

For further details, refer to the relevant GitHub issue and the corresponding source file.

It is not as straightforward as using typeChecker.getSymbolAtLocation. Consider the example below:

function someScope() {
    let myInt = 0;
    let myFloat = 0;

    for (let i = 0; i < 3; i += 1) {
        myInt = i;
        myFloat = i;
    }

    if (external) {
        myInt = 7;
    } else {
        myFloat = 7.5;
    }

    return myInt * myFloat;
}

The objective is to develop a program that traverses the tree and correctly identifies myInt as an integer (not just a generic number) while recognizing myFloat as a float. Additionally, the function someScope should be understood to return a float (not an integer).

In the "worst-case" scenario, the strategy would involve analyzing the variables' containing scope, finding all references to them, and recursively determining their types. Surely, there must exist a standard method to achieve this?

Answer №1

If you want to achieve this, follow these steps:

const ts = require('typescript');
const service = ts.createLanguageService(host);
let identNode;
function search(node) {} // ...search and locate the declaration of your identifier
for (const file of service.getProgram().getSourceFiles()) {
    if (!file.isDeclarationFile) {
        ts.forEachChild(file, search);
    }
}
const refs = service.findReferences(identNode.getSourceFile().fileName, identNode.getStart());
const refNodes = new Set();
refs?.forEach(ref => {
   const { references } = ref;
   references?.forEach(reference => {
       const sourceNode = service.getProgram().getSourceFile(reference.fileName);
       ts.forEachChild(sourceNode, node => {
           // explore items..., apply logic like:
           // if node.textSpan === references.textSpan
           // refNodes.add(node);
       });
   })
})

The "refNodes" variable contains what you are looking for. For a similar code example, check out this link

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The ReplaySubject is receiving an updated response, however, the View is displaying the same information

Having an issue with the ReplaySubject in my code. It seems that after updating an Array, the new values are not reflecting on the UI. I can only see the old values unless I reload the page. I have tried using ngZone but it didn't help. The code is d ...

What is the reason for VS Code not displaying doc comments from type properties when suggesting descriptions and hover info for TypeScript objects?

The problem is clearly visible in the image below, as it pertains to the popup box in VSCode displaying type information and comments. https://i.sstatic.net/rncRy.png Although the code works fine in VSCode, TypeScript Playground fails to display the comme ...

Unable to utilize Next/Link in a NextJs 13 application directory

After enabling the appDir feature in Next.js 13, I encountered an error when adding a Link component: import Link from 'next/link'; function Header() { return ( <div> <Link href="/">Home</Link> </ ...

Stop the observable interval in Angular when the route changes

I initiated an interval in an Angular component, but the requests are still being made even when I navigate to a different route. How do I halt the interval? //function that returns an observable getAllPolls() { return Observable.interval(2000).swit ...

Webpack encountered an error regarding an unidentified variable: babelHelpers

I'm currently developing a React application and using react-router-dom along with typesafe-react-router for routing. My project is configured with webpack 4 and Babel. I have defined my routes in a file named routes.ts: import { route } from 't ...

What is the best way to go back in Angular 5 - using href or location.back()?

I recently encountered a dilemma with my app where users navigate to a dead-end page without any way to return. Picture clicking on a program in a TV guide and getting stuck on that program's details page, not being able to go back to the main guide. ...

What is the meaning of boolean true in a Firestore query using TypeScript?

Currently, I am facing an issue with querying Firestore in Angular 8 using AngularFire. While querying a string like module_version works perfectly fine as shown in the code snippet below, the problem arises when attempting to query a boolean field in Fire ...

The top border of the chart should be overlaid by the Highcharts Flag Series

My goal is to create a flag series that sits atop all plotLines in my chart, overlaying the top edge of the chart. Despite manually changing various components within the Highcharts component using Chrome DevTools and setting overflow: visible, I have not ...

The arrow function in Jest is missing a name property

Currently, my setup includes: node.js: 9.8.0 Jest: 23.4.2 ts-jest: 23.1.3 typescript: 2.9.2 While attempting the following in my *.test.ts files: const foo = () => 'bar'; console.log(foo.name); // '' foo contains the name pro ...

Definition of Promise resolve type in Visual Code's d.ts file

Need help with: // api.js export function getLayout(){ return axios.get('/api/layout').then(res => res.data) } // api.d.ts declare interface JSONResponse { meta: object, data: Array<Field> } export declare function getLayout ...

What is the best way to apply filtering to my data source with checkboxes in Angular Material?

Struggling to apply datatable filtering by simply checking checkboxes. Single checkbox works fine, but handling multiple selections becomes a challenge. The lack of clarity in the Angular Material documentation on effective filtering with numerous element ...

Fetching URL from Right Before Logging Out in Angular 2 Application

I am struggling to capture the last active URL before logging a user out of my Angular 2 app. My goal is to redirect them back to the same component or page once they log back in. Currently, I am using this.router.routerState.snapshot['url'] to r ...

I am unable to import choices.js using the "import" command in TypeScript

I'm having trouble importing choices.js using the "import" command: import Choices from 'choices.js'; TS2307: Cannot find module 'choices.js' The following attempts didn't work either: import Choices from '../../node_ ...

What could be the reason for the lack of impact when assigning a [dateClass] in mat-calendar?

I've been trying to customize the appearance of specific days in the mat-calendar component from Angular Material, but I'm having trouble getting it to work. I discovered the dateClass property which seemed like the right solution, but no matter ...

Angular 2: The Art of Detecting Changes

I have successfully integrated Angular 1 and Angular 2 by creating an Angular 1 controller and service, along with an Angular 2 component. These components work seamlessly together for data retrieval and storage. Here is a snippet of my HTML page: <bod ...

Function generation using TypeScript

I'm in the process of creating a tool to automatically generate boilerplate code for me. The concept involves parsing all .json files within a folder called config, and then creating interfaces and auxiliary functions based on that data. Thanks to t ...

Support for Typescript in Polymer version 3

Currently experimenting with Polymer 3 preview to explore how it can be integrated into our team workflow. The recommended method for declaring an element in v3 is as follows: import { PolymerElement } from '@polymer/polymer/polymer-element.js' ...

Utilize a segment of typography to craft a brand new design

Recently, I created a type known as TranslationsData: [key: string]: { translation: { state: AnotherType } }; Now, I am looking to incorporate this section: [key: string]: { translation: { state: into another type, with the only modification being the An ...

React component stuck in endless loop due to Intersection Observer

My goal is to track the visibility of 3 elements and update state each time one of them becomes visible. Despite trying various methods like other libraries, useMemo, useCallback, refs, etc., I still face challenges with my latest code: Endless loop scenar ...

What could be causing my vis.js network's node hover popups to not function properly?

I've encountered an issue where, despite adding the 'title' property to my node objects, the pop up window with the title content doesn't appear when I hover over a node. Here are the options I've chosen and how I've set up m ...