typescript-transformer-handbook
typescript-transformer-handbook copied to clipboard
Usage question: Adding a child node
Hello again!
Sorry for using this channel again asking a general usage question. But I really appreciated your help the last time.
How can I or how would you add a child node to a given node?
E.g. add static instances = [];
to class Test {}
.
I know that I can find the class declaration with ts.isClassDeclaration(node)
but how would you proceed then?
Do I really have to provide a new class declaration node (like in the code snippet) or is there a more "elegant" way?
if (ts.isClassDeclaration(node) {
// createInstancesProperty ==> custom fn to create "static instances = [];"
const extendedMembers = ts.createNodeArray([createInstancesProperty(symbol.name), ...node.members]);
return ts.createClassDeclaration(node.decorators, node.modifiers, node.name, node.typeParameters, node.heritageClauses, extendedMembers);
}
I am wondering what's the best approach if I would like to do something (on) ...
-
Add a static property to the class || e.g.
static instances = [];
-
ts.isConstructorDeclaration
- add content to the constructor if there is one || e.g.
ClassName.instances.push(this)
- add the constructor and the content if there is none
-
ts.isMethodDeclaration
-
ts.isPropertyDeclaration
I really enjoy using the visitor pattern approach but I do not know how to use it in combination with my desired tasks 1) and 2).
Any help appreciated. Thanks in advance.
Hi! No worries happy to help
In this instance I'm not sure if there is a better way
In general you basically want to do it by a process of elimination until you get to the node you actually want to change, so I might have something in an if statement i want to change
i could check
- is one of this nodes parents an if statement that i care about
- is this node the node i care about
then just return a new/updated node
I don't think there's any silver bullet - it's just using the tools in such a way that helps us achieve what we want 😄
Okay okay. But how would you tackle the described tasks together then? If I got you correctly my approach regarding returning a new class declaration node wasn’t to bad. At least that’s how I achieved adding the static property to the class.
But in my case (or at least in one of the tasks) it is in general not about changing a specific node; it is more about inserting a child node. Otherwise I would get what you are suggesting.
But how would you now additionally transform/adjust the property declarations of the class? E.g. transforming all numbers to strings. (the use case does actually not really matter)
Do you know what I mean / what my problem is? Referencing the previous code snippet: Just modifying the node (without the visitor pattern and returning a VisitorResult) will not do the trick. At least what I experienced so far.