如何访问 typescript ast api 中的 FlowNode?

How to access FlowNode in typescript ast api?

我尝试从 nodes 变量解析 foobar

我在 ts-ast-viewer 上查看后,您可以在图片中看到 typescript 可以从 FlowNode 部分下的 nodes 节点了解 foobar。 (节点 -> 初始值设定项 -> 元素 -> escapedText (foo, bar))。

但是如何访问 FlowNode?

我使用 ts-morph 来处理我的打字稿 ast 代码。我已经有了 nodes 标识符。不幸的是,我无法访问我在 FlowNode 部分看到的属性:

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

完整代码:

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

流节点目前未在 ts-morph 中公开,并且实际上并未真正公开在编译器 API 的类型声明中,但您仍然可以访问它们。

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 });

我已经打开 https://github.com/dsherret/ts-morph/issues/1276 以便将来更容易。