[英]TypeScript Compiler API: Accessing resolved type of 'this' parameter
Using the compiler API, I need to access the real type of an explicit 'this' parameter from a ts.Signature. 使用编译器API,我需要从ts.Signature访问显式“ this”参数的实型。
// 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. 当前,我可以调用getDeclaration()并查看适用于Fn1的参数。 But it for Fn2, it won't resolve 'T' to 'void'.
但是对于Fn2,它不会将“ T”解析为“ void”。 When tracing through with the debugger, I can see signature has a member called 'thisParameter' which seems like it has what I need.
使用调试器进行跟踪时,我可以看到签名有一个名为“ thisParameter”的成员,看来它具有我所需要的。 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?
有没有办法正确访问类型?
To get the this parameter type from the signature, it seems you will need to access the internal thisParameter
property. 要从签名中获取此参数类型,似乎您需要访问内部的
thisParameter
属性。 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: 在这种情况下,
ts.Type
是ts.TypeReference
因此:
const type = checker.getTypeAtLocation(node.type!) as ts.TypeReference;
const typeArg = type.typeArguments![0];
console.log(typeArg); // void
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.