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:
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