I am trying to parse a class and create default values of the property declarations that does not have values on the declaration.
For example from this:
class MyClass {
name = 'My Class';
id: string;
}
functionCall<MyClass>() // <-- I get the hold of the type class here
I want to generate something like this:
{
name: 'My Class',
id: 'I am generated'
}
I get MyClass
from functionCall<MyClass>
as type: ts.InterfaceType
node and from there I parse the properties:
const typeChecker = program.getTypeChecker();
const type = typeChecker.getTypeAtLocation(callExpression); // This is the node where `functioCall<MyClass>()` is
type.getProperties().forEach(symbol => {
// I am stuck here
});
The problem I have there, is that some symbols
have symbol.valueDeclaration
as undefined and I do not know what to use to know
I though check if a symbol.valueDeclaration
exist and if their symbol.valueDeclaration.kind
is some keyword (like SyntaxKind.StringKeyword
) but it would not work for something like
class SomeClass {
noKeyword; // probably any?
}
Any help or pointers would be appreciated.
I was almost there, I needed to check if in the children of the valueDeclaration
a literal was defined
const propertyDeclaration = symbol.valueDeclaration;
if (ts.isPropertyDeclaration(propertyDeclaration)) {
const children = propertyDeclaration.getChildren();
const assignationLiteral = children.find(child => {
ts.isLiteralTypeNode;
return [
ts.SyntaxKind.NumericLiteral,
ts.SyntaxKind.StringLiteral,
ts.SyntaxKind.ObjectLiteralExpression,
].includes(child.kind);
});
if (assignationLiteral) {
// A value es defined!
} {
// I have a keyword, I have to check which one is it :)
}
}