Add refactor convertToOptionalChainExpression by jessetrinity · Pull Request #39135 · microsoft/TypeScript (original) (raw)
Most of your test cases are expression statements, but expression statements that don’t immediately contain call expressions are somewhat rare. If the idea is to automatically find a suitable expression node from a zero-width span, I think you could try just walking up ancestors until you see something that’s unlikely to be part of an expression you can transform, like a statement. For example, say you have
return foo(a && a.b && a.b/|/.c);
You start on an Identifier, and walk up because an Identifier is obviously part of something you could transform. One parent up is a PropertyAccessExpression, which could also be part of a candidate, so you keep walking. Another PropertyAccessExpression, keep going. A BinaryExpression with an && token, keep going, while saving this node as a candidate expression. Now, since you have a candidate BinaryExpression, I think you’d want to continue only if the next parent is also a candidate BinaryExpression. It’s not, so you use the BinaryExpression as the potential node to transform.
I’m probably oversimplifying this in my head, but I think you at least want to make sure the refactor works for
- return statement expressions
- call arguments
- variable initializers
in addition to ExpressionStatements.