What is the procedure for obtaining FlowNode in the typescript ast api?

Trying to access and resolve foo and bar from the nodes variable.

Upon examination in ts-ast-viewer, it is evident that TypeScript recognizes foo and bar within the nodes node under the FlowNode section (node -> initializer -> elements -> escapedText (foo, bar)).

The question arises: How can one access the FlowNode?

Utilizing ts-morph for working with TypeScript AST code, the nodes Identifier is already available. However, accessing the properties visible in the FlowNode section proves challenging:

console.log({ n: nodes.node }); // <-- note that 'node' is not present in 'nodes', as illustrated in the picture.

The complete code snippet can be found here:

codesandbox

import { Project, SyntaxKind } from "ts-morph";

console.clear();

const project = new Project({
  skipAddingFilesFromTsConfig: true
});

const sourceFile = project.createSourceFile(
  "foo.ts",
  `
const items = [foo, bar];
const nodes = [...items];
  `
);

const nodes = sourceFile
  .getDescendantsOfKind(SyntaxKind.Identifier)
  .find((n) => n.getText() === "nodes");

console.log({ n: nodes.node.initializer }); // <-- error: 'node' is undefined

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

Answer №1

At this time, Flow nodes are not directly accessible in ts-morph or the compiler API's type declarations. However, there is a workaround to still retrieve them.

import { Project, ts } from "ts-morph";

console.clear();

const project = new Project({
  skipAddingFilesFromTsConfig: true
});

const sourceFile = project.createSourceFile(
  "foo.ts",
  `
const items = [foo, bar];
const nodes = [...items];
  `
);

// get the identifier
const nodesIdent = sourceFile
  .getVariableDeclarationOrThrow("nodes")
  .getNameNode();

// hack to force the type checker to create the flow node
nodesIdent.getType();

// get the flow node
const flowNode = (nodesIdent.compilerNode as any).flowNode as ts.FlowNode;

console.log({ n: flowNode });

I have submitted https://github.com/dsherret/ts-morph/issues/1276 to address this for future ease of access.

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

How to retrieve a stored value using Ionic 3 native storage

Hey there, I recently attempted to implement code from the Native Storage plugin documentation found at this link: Native Storage import { NativeStorage } from '@ionic-native/native-storage'; constructor(private nativeStorage: NativeStorag ...

Using Angular, a function can be called recursively directly from within the HTML

I'm struggling with loading an image because the method getUserProfileImage() is getting triggered multiple times within a loop. Is there a way to ensure the method is only called once during each iteration? I understand that this issue is related to ...

Tips on typing a collection that may hold numerous instances of a particular object

When working with NgRx actions, I need to define the parameter. This parameter is an object that can contain a varying number of specific objects. These objects are already defined in an Interface. export interface CustomDistribution { maxWindowsActive ...

Is it possible for TypeScript to mandate abstract constructor parameters?

This specific function is designed to take a constructor that requires a string argument and then outputs an instance of the constructed value T: function create<T>(constructor: new(value: string) => T): T { return new constructor("Hello& ...

Combine TypeScript files in a specific sequence following compilation

I am hoping to utilize gulp for the following tasks: Compiling TypeScript to JavaScript, which is easily achievable Concatenating JavaScript files in a specific order, proving to be challenging Since I am developing an Angular application, it is crucial ...

Creating a Personalized Color Palette Naming System with Material UI in TypeScript

I have been working on incorporating a custom color palette into my material ui theme. Following the guidance provided in the Material UI documentation available here Material UI Docs, I am trying to implement this feature. Here is an excerpt from my cod ...

Exploring depths with Typescript recursion

I'm attempting to implement a recursive search in Typescript, but I am encountering an issue where TS is unable to determine the return type of the function. function findDirectory( directoryId: Key, directory: Directory, ) { if (!directory) ret ...

Discovering the ASP.NET Core HTTP response header in an Angular application using an HTTP interceptor

I attempted to create a straightforward app version check system by sending the current server version to the client in the HTTP header. If there's a newer version available, it should trigger a notification for the user to reload the application. Ini ...

Reduce the size of the JSON file located in the Assets folder during an Angular build

What is the most effective method to compress JSON files in an Angular production build? I currently have a JSON file in the assets folder that remains unchanged when the production build is completed. During development, the file appears as the Developme ...

"Experiencing sluggish performance with VSCode while using TypeScript and Styled Components

My experience with vscode's type-checking is frustratingly slow, especially when I am using styled components. I have tried searching for a solution multiple times, but have only come across similar issues on GitHub. I attempted to read and understa ...

Typescript's Confusion with Array Types: Understanding Conditional Types

Here is the setup I have. The concept is to receive a generic and options shape, deduce the necessary options based on the generic and the type key of the options shape, and appropriately restrict the options. type OptionProp<T extends string | boolean& ...

Creating an array with varying types for the first element and remaining elements

Trying to properly define an array structure like this: type HeadItem = { type: "Head" } type RestItem = { type: "Rest" } const myArray = [{ type: "Head" }, { type: "Rest" }, { type: "Rest" }] The number of rest elements can vary, but the first element ...

What is the best way to create a case-insensitive sorting key in ag-grid?

While working with grids, I've noticed that the sorting is case-sensitive. Is there a way to change this behavior? Here's a snippet of my code: columnDefs = [ { headerName: 'Id', field: 'id', sort: 'asc', sortabl ...

Get notified with ng2-smart-table updates when editing

I am trying to control the edit feature of my ng2-smart-table, but the code I have isn't working. Am I missing something? HTML <ng2-smart-table [settings]="settings" [source]="source" (edit)="onEdit($event)"></ng2-smart-table> Component ...

Filtering JSON data in Ionic 4 based on multiple values

Recently, I've encountered an issue with filtering a local JSON file based on multiple criteria. Initially, I thought that combining conditions using '&&' would solve the problem. However, when the data is loaded into Ngx-Datatable, nothing ...

Navigating UnwrapRefSimple in Vue Composition API and TypeScript: Best Practices

When I utilize reactive objects in Vue Composition API, I encounter Typescript errors relating to UnwrapRefSimple<T>. This issue appears to be specifically tied to using arrays within ref(). For instance: interface Group<T> { name: string ...

Tips for invoking a function from one React component to another component

Currently, I am working on two components: one is Game and the other is PickWinner. The Game component serves as the parent component, from which I need to call the pickWinner function in the PickWinner component. Specifically, I want to trigger the startP ...

Issue with the recursive function in javascript for object modification

I have all the text content for my app stored in a .json file for easy translation. I am trying to create a function that will retrieve the relevant text based on the selected language. Although I believe this should be a simple task, I seem to be struggl ...

Encountering an error while compiling the Angular 8 app: "expected ':' but got error TS1005"

As I work on developing an Angular 8 application through a tutorial, I find myself facing a challenge in my header component. Specifically, I am looking to display the email address of the currently logged-in user within this component. The code snippet fr ...

What is the best way to include a string index signature in a preexisting Array?

Currently, I am immersed in styled-system and attempting to define a pattern that is frequently employed within the library. const space: { [key: string]: string } = [ '0.25rem', '0.5rem', '1rem', '2rem', ...