Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to access FlowNode in typescript ast api?

I try to resolve foo and bar from nodes variable.

After I checked at ts-ast-viewer you can see in the picture that typescript can know about foo and bar from nodes node, under FlowNode section. (node -> initializer -> elements -> escapedText (foo, bar)).

But how I can access FlowNode?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I using ts-morph to work on my typescript ast code. and I already have the nodes Identifier. unfortunately I can’t access to the properties I can see in the FlowNode section:

console.log({ n: nodes.node }); //<-- node not exist in nodes but I can see this in picture.

The full code:

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

enter image description here

>Solution :

Flow nodes aren’t exposed in ts-morph at the moment and aren’t actually really exposed in the compiler API’s type declarations, but you can still access 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’ve opened https://github.com/dsherret/ts-morph/issues/1276 to make this easier for the future.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading