Я пытаюсь разрешить foo и bar из переменной nodes.
После того, как я проверил в ts-ast-viewer, вы можете видеть на картинке, что typescript может знать о foo и bar из узла nodes в разделе FlowNode. (узел -> инициализатор -> элементы -> экранированный текст (foo, bar)).
Но как я могу получить доступ к FlowNode?
Я использую ts-morph для работы над своим машинописным кодом ast. и у меня уже есть идентификатор nodes. к сожалению, я не могу получить доступ к свойствам, которые я вижу в разделе FlowNode:
console.info({ n: nodes.node }); //<-- node not exist in nodes but I can see this in picture.
Полный код:
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.info({ 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.info({ n: flowNode });
Я открыл https://github.com/dsherret/ts-morph/issues/1276, чтобы упростить задачу в будущем.