ts-morph
ts-morph copied to clipboard
Inject references to existing types into generated code
I'm rewriting this issue since I have a better definition of what I want to do now..
Suppose I have a Type
instance which I've somehow obtained from existing code and I want to generate new code which uses that Type
. If the type represents e.g. an interface, then that interface is defined somewhere, and so the generated code will need to import it in order to use it. What is the best / correct way to go about this? I'm fumbling in the dark a bit, because I'm not entirely sure about the terminology - ie. what is a type, what is a symbol etc - but for example if the Type
represents a class, I know I can do something like type.getSymbol()?.getValueDeclaration()?.getSourceFile()
to get the file where the class is declared; I can then resolve the import specifier using a method of the generated source file (I think I've seen something like that in IntelliSense). I can probably also resolve the name of the type from its symbol so that I know what to import. But I'm completely unsure if this is the right way to do this - I'm only going through the symbol because I found out it has a .getName()
method, whereas the type does not. And also it seems as though there might be a better way to do this, because SourceFile
has the .fixMissingImports()
method, which afaik delegates to the language service, and so I'm wondering if there may be a way to use the language service to help with this..?