typescriptabstract-syntax-treetypescript-compiler-api

How to stop current traversal of visitEachChild in TypeScript Transformer API?


When visiting each node of a parent node, using visitEachChild, how can I stop it when I no longer want to visit the next child nodes, for example:

How can you stop the tour? That is, I don't want to continue or iterate Node 3, 4, 5, etc., something like a "break".

For example:

class A {
    public template() { // <-- I just want to get here.
        return 'Template';
    }

    someThing() {}

    foo() {}
}

Transformer:

const transformerFactory: ts.TransformerFactory<ts.Node> =
    (context: ts.TransformationContext) => (rootNode) => {
        const visit = (node: ts.Node): ts.Node => {            
            if (ts.isClassDeclaration(node)) {
                ts.visitEachChild(node, (child) => {
                    if (ts.isMethodDeclaration(child)) {
                        console.log(child.name.getText());
                        
                        if (child.name.getText() === 'template') {
                            
                            return "I don't want to move to the siblin node. break here!!!";
                        } else return child;
                    } else return child;
                }, context);
                return node;
            }
            return ts.visitEachChild(node, visit, context);
        };

        return ts.visitNode(rootNode, visit);
    };

Solution

  • In this case you might just want to look at the class declaration's members property array directly. If not, then use ts.forEachChild and return a value to stop going through the children (note the value returned in the provided function will be the value returned by ts.forEachChild).