Hello,
I would like to extract the value "[button]" of the generic type below for example:
type Component<type, selector> = type;
definition class MyComponent {
static selector: Component<string, '[button]'>;
}
I did :
const type = source.getClass('MyComponent').geStaticProperty('selector').getType();
type.getTypeArguments().map(a => a.getText()); // [ 'string' ]
It looks like getTypeArguments returns the value returned by the type and not the text.
Unfortunately I cannot use type.getText() and string manipulation because the realworld usecase is too complex.
I was looking for something like type.isGeneric() ? type.getGeneric() : [] but did find anything that looks like that.
Thanks for the help :)
@GrandSchtroumpf I get the following output instead:
type.getTypeArguments().map(a => a.getText()); // []
What's going on here is the TS compiler is "interning" the type to string. Try doing type.getText() and you will see it's a string. That's done for performance reasons in the compiler (I wish there was a way to disable it)... see this answer from the TypeScript team.
In this scenario, instead of getting the type you can get the type node. Here's an example:
const project = new Project({ useInMemoryFileSystem: true });
const file = project.createSourceFile("file.ts", `type Component<type, selector> = type;
definition class MyComponent {
static selector: Component<string, '[button]'>;
}`);
// Using https://ts-ast-viewer.com can be useful to figure out what these nodes are...
// You can also use the functions like `Node.isTypeReferenceNode(node)` to check
// if a node is of a certain kind.
const propertyDec = file.getClassOrThrow('MyComponent')
.getStaticPropertyOrThrow('selector') as PropertyDeclaration;
const typeNode = propertyDec.getTypeNodeOrThrow() as TypeReferenceNode;
console.log(typeNode.getTypeArguments().map(a => a.getText())); // ['string', "'[button]'"]
Amazing, thanks a lot !! So many kind of nodes ^^.
Why using TypeNode would work better than getType ?
It's a common source of confusion due to somewhat bad naming, but I'm not sure what would be better. getType() returns the type from the type checker (shown in purple in the image below) and getTypeNode() returns the node from the AST (shown in blue).
