Nexx
Nexx

Reputation: 407

Typescript transformer, `node.parent` is undefined

I'm currently using a typescript transformer api, and I found that the node.parent is undefined.

My code is:

        const transformerFactory: ts.TransformerFactory<ts.Node> = (
            context: ts.TransformationContext
        ) => {
            return (rootNode) => {
                function visit(node: ts.Node): ts.Node {
                    node = ts.visitEachChild(node, visit, context);

                    // HERE node.parent IS UNDEFINED !

                    return filterFn(node, context);


                }
        
                return ts.visitNode(rootNode, visit);
            };
        };
        
        const transformationResult = ts.transform(
            sourceFile, [transformerFactory]
        );

How can I find the parent of the node?

Upvotes: 5

Views: 846

Answers (1)

David Sherret
David Sherret

Reputation: 106580

You can parse specifying to set the parent nodes:

const sourceFile = ts.createSourceFile(
    "fileName.ts",
    "class Test {}",
    ts.ScriptTarget.Latest,
    /* setParentNodes */ true, // specify this as true
);

Or do some operation on the node to get it to set its parent nodes (ex. type check the program... IIRC during binding it ensures the parent nodes are set).

Update based on comment

If you are creating these from a program, then you can do the following:

const options: ts.CompilerOptions = { allowJs: true };
const compilerHost = ts.createCompilerHost(options, /* setParentNodes */ true);
const program = ts.createProgram([this.filePath], options, compilerHost);

Upvotes: 5

Related Questions