[Question] What's the best way to get the constructors of all the parameters of a method?
See original GitHub issueHey there!
First of all, congratulations on this AMAZING AMAZING AMAZING project! Iām astonished by the flexibility it provides and how much easier it is than using the typescript compiler API.
Iām a beginner to the typescript compiler API, so I still have some questions:
Say I have this example code
type Person = {
firstname: string;
age: 34;
};
class Place {
private lat;
private lng;
constructor(lat: 123, lng: 543) {
this.lat = lat;
this.lng = lng;
}
}
export class Animal {
bark(toWhom: Person, howManyTimes: 4) {
return "bark!";
}
}
I want to create a program that given a class name (say Animal
), will pick a random method of it (say bark
) and call it with parameters that make sense.
For that, I need to be able to
- Given a class name, get the class
- Given a class, get all the methods
- Given a specific method get all the parameters
- Given a list of parameters, get their respective types
- Given a list of types, get how to construct an instance of each type.
Iāve managed to solve 1-4. However 5) is eluding me.
Hereās what I have so far
import { Project } from "ts-morph";
const project = new Project({
tsConfigFilePath: "./tsconfig.json",
});
const sourceFiles = project.getSourceFile((f) => f.getClasses().length === 2);
const aClass = sourceFiles?.getClasses()[1]; // Animal
const methods = aClass?.getMethods();
const aMethod = methods![0]; // Animal.bark
const theParams = aMethod.getParameters();
const aParam = theParams[0]; // toWhom
const paramType = aParam.getTypeNode();
console.log(paramType?.getKindName()); // TypeReference
console.log(paramType?.getText()); // Person
Now I need to get āaholdā of the Person class in order to be able to read its constructor and the types of the constructor params to know how to create an instance of it.
But how would I go about doing that?
Issue Analytics
- State:
- Created 3 years ago
- Comments:5 (3 by maintainers)
Top GitHub Comments
@mikealche oh, my bad! I mixed this up in my head and was acting like this was
typeof Person
.In this case, you can get the parameterās type, then from the type go to the symbol and then to the class declaration:
@mikealche no problem! š Feel free to open another issue if you have more questions.