Followup of Find node of specific SyntaxKind in ASL tree with typescript compiler api but focused on return statements for future googlers.
I would like to find return statements in a method body with the typescript compiler api.
My function body is unknown, so I hope to not have to access the different nodes statically. I found there is a function visitFunctionBody but that requires a context. The example I've seen seem to get a context from a transformer factory but typescript does not export such a member anymore and I'm not even sure this does what I need to do.
So how can one find return statements in a body ?
I've tried something along the lines of:
function findReturnStatements() {
const children: Node[] = [];
node.forEachChild((childNode) => {
children.push(childNode);
});
return node.filter(isReturnStatement);
}
But this can fail depending on the shape of the body
someMethod() {
return 3;
}
// vs
someMethod() {
try {
return 3;
} catch (e) {
return 4;
}
}
You probably want something like this:
Note that arrow functions can have a consise body, which is just an expression (ex.
() => 1), so that's why it returnsts.Expressionin addition tots.ReturnStatement.