Identifying arrow functions using the Typescript Compiler API: A guide

I've been trying to mimic the example provided in the TypeScript wiki on Using the Type Checker but I'm having trouble detecting arrow functions.

For instance:

/**
 * Hello
 */
export const hello = (): string => 'hello';

My visitor doesn't recognize this as an arrow function:

function visit(node: ts.Node) {
   console.log(node.kind, ts.isArrowFunction(node)); // -> 236, false

However, standard functions are being correctly identified:

For example:

/**
 * Hello
 */
export function hello (): string {return 'hello'};

This is recognized by the visitor using isFunctionDeclaration

function visit(node: ts.Node) {
   console.log(node.kind, ts.isFunctionDeclaration(node)); // -> 255, true

What am I missing here? How can I successfully detect arrow functions?

Answer №1

Check out this code snippet on ts-ast-viewer.com:

https://i.sstatic.net/SDHbJ.png

Upon inspection, you'll notice a nested structure starting from a VariableStatement all the way to an ArrowFunction initializer within a VariableDeclaration.

You can also traverse recursively downwards as shown below:

function findDescendantArrowFunction(node: ts.Node) {
  if (ts.isArrowFunction(node)) {
    return node;
  } else {
    return ts.forEachChild(node, findDescendantArrowFunction);
  }
}

const arrowFunc = findDescendantArrowFunction(sourceFile);

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 delay function in RxJS allows for waiting to return a value until a specific condition is met within a stream and

Currently, I am facing an issue with a method in my application that triggers a server request. This method has access to a stream from the redux-store and needs to execute a callback only when the result of the request is found in the mentioned stream. Th ...

Utilizing Angular 4 to dynamically load a recursive template with input values

Currently, I am developing a component that functions similar to a treeview. Below is the template for my tree-view: <div>{{templateData?.text}}">1</div> <div class="row" *ngFor="let child of templateData?.children"> <tree-view ...

Errors in Intellisense detected within the latest Node Tools Express App development project

After setting up a new project with the "Basic Node.js Express 4 Application" template, I noticed some errors have already surfaced: https://i.sstatic.net/8jbYt.png Could this be a Visual Studio issue? Any pointers on resolving these errors? ...

Guide to effectively executing a GET request in React that returns an observable without relying on promises, similar to the approach in Angular

When working with Angular, my usual approach involves subscribing to a client that provides me with an observable from a GET call as per Google's recommendations. httpClient.get<Data>("http://blah") .subscribe( result => { ... }, e ...

Merging declarations fails to function properly following the release of the npm module

The file core.ts contains the definition of a class called AnyId. In another file named time.ts, more methods are added to the AnyId class. This is achieved by extending the type of AnyId using declaration merging: declare module './core' { in ...

How to extract a specific property from data using Angular's HttpClient-subscribe

It seems like this question has been asked before, but I can't seem to find the answers or know what terms to search for. I have a JSON file structured like this: { "pages": [{ "displayname": "PageA", "url": "http://google.de", " ...

Error: global not declared in the context of web3

I've been attempting to integrate Web3 into my Ionic v4 project for some time now. However, I keep encountering errors when I try to serve the project. Specifically, I receive an error message stating that Reference Error: global is not defined. Cre ...

The parameter type 'DateInput' cannot be assigned to the parameter type 'Date'

I am currently utilizing fullcalendar for my project. However, I would like to utilize my local models instead of fullcalendar's model. The issue arises when attempting to create a new instance of my own model, as it displays the following error messa ...

Testing the Angular router-outlet using Jasmine

When testing web-app navigation using Jasmine spec with RouterTestingModule, I am facing challenges with nested fixture.whenStable().then(() => {}). For instance: After clicking on multiple links where the router-outlet changes the displayed component ...

Removing multiple items from a list in Vue JS using splice function

I have a problem with my app's delete feature. It successfully deletes items from the database, but there seems to be an issue in the front-end where I can't remove the correct items from the list. Check out this demo: https://i.sstatic.net/eA1h ...

LeafletModule was unable to be identified as an NgModule class within the Ivy framework

Currently working on an angular project using ngx-leaflet. Upon initiating ng serve in the terminal, the following error message pops up: Error: node_modules/@asymmetrik/ngx-leaflet/dist/leaflet/leaflet.module.d.ts:1:22 - error NG6002: Appears in the NgMod ...

React-pdf has encountered a situation where more hooks were rendered compared to the last render cycle

I am currently integrating react-pdf to display a PDF document in a web view. The React application is built with TypeScript and Next.js. This is the code I have written so far: const MyPage: NextPage = () => { // some code here const [numPages, setN ...

Is there a way to sort through nested objects with unspecified keys?

I'm looking to extract specific information from a nested object with unknown keys and create a new array with it. This data is retrieved from the CUPS API, where printer names act as keys. I want to filter based on conditions like 'printer-stat ...

What is the reason behind being unable to register two components with the same name using React Hook Form?

I have encountered an issue while using the useForm hook from React Hook Form library. Due to the specific UI library I am using, I had to create custom radio buttons. The problem arises when I try to register two components with the same name in the form ...

What is the purpose of importing Vue in my .d.ts file?

I am confused about the necessity of importing Vue in my .d.ts file. The official website mentions to "Make sure to import 'vue' before declaring augmented types", but I don't understand why this is required. https://v2.vuejs.org/v2/guide/ty ...

Where should an EventListener be added in an Angular Service Worker?

I am currently in the process of developing an Angular Progressive Web Application (PWA) with offline capabilities. While I have made significant progress, I am facing challenges regarding events for the service worker. Specifically, I am unsure about wher ...

Deduce the general subclass within a dynamic data structure

My goal is to develop a configuration management class with key mapping and resolution strategies. I want to create an accessor function that can retrieve the value along with its correct data type from the dynamic map. type ParameterDescription<T> = ...

Rearrange AxisX and AxisY in Lightningchart library

I am currently utilizing the lightningchart library and intend to create a ChartXY with an AreaSeries attached to it. To achieve this, I have written the following code using React and TypeScript: import { useEffect, useRef } from 'react'; impor ...

After deploying my app, the only thing I see is a blank page staring back at

Looking for assistance with my React app. I made a decision to incorporate Vite into my React application to address some performance issues after the initial development. Everything is functioning smoothly in my local environment; however, once deployed ...

Enhance a function by sending it back to save static variables

I have a similar function like this one: export const bar = function () { const myItem = new MyItem(); return function bar(param1?: number, param2?: string): void{ ... }; }(); Where myItem is a variable that I use as a temporary inside ...