5

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?

2
  • The root node has no parent. Commented Mar 12, 2021 at 17:09
  • 1
    I don't get parent for every other node Commented Mar 12, 2021 at 17:12

1 Answer 1

5

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Is this possible if I have this.program = ts.createProgram([this.filePath], { allowJs: true }); this.sourceFile = this.program.getSourceFile(this.filePath); ?
@nexis no problem!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.