Issue
Using the compiler API, I need to access the real type of an explicit 'this' parameter from a ts.Signature.
// Code being compiled
interface Fn1 {
(this: Foo): void;
}
const fn1: Fn1 = () => {};
interface Fn2<T> {
(this: T): void;
}
const fn2: Fn2<void> = () => {};
// Compiler API
function visitVariableDeclaration(node: ts.VariableDeclaration, checker: ts.TypeChecker) {
const type = checker.getTypeAtLocation(node.type);
const signatures = checker.getSignaturesOfType(type, ts.SignatureKind.Call);
const signature = signatures[0];
// How do I access type of 'this' on signature?
}
Currently, I can call getDeclaration() and and look at the parameters, which works on Fn1. But it for Fn2, it won't resolve 'T' to 'void'. When tracing through with the debugger, I can see signature has a member called 'thisParameter' which seems like it has what I need. But this is not publicly exposed through the interface, so I can't really depend on that. Is there a way to properly access the type?
Solution
To get the this parameter type from the signature, it seems you will need to access the internal thisParameter
property. For example:
const thisParameter = (signature as any).thisParameter as ts.Symbol | undefined;
const thisType = checker.getTypeOfSymbolAtLocation(thisParameter!, node.type!);
console.log(thisType); // void
Alternatively, it's possible to get it from the type directly. In this case the ts.Type
is a ts.TypeReference
so:
const type = checker.getTypeAtLocation(node.type!) as ts.TypeReference;
const typeArg = type.typeArguments![0];
console.log(typeArg); // void
Answered By - David Sherret
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.