TypeScript 编译器 API:访问解析的'this'参数类型



使用编译器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?
}

目前,我可以调用getDeclaration((并查看参数,它适用于Fn1。但对于Fn2,它不会将"t"解析为"void"。当使用调试器进行跟踪时,我可以看到签名有一个名为"thisParameter"的成员,它似乎符合我的要求。但这并不是通过界面公开的,所以我不能真正依赖它。有没有一种方法可以正确访问类型?

要从签名中获取此参数类型,似乎需要访问内部thisParameter属性。例如:

const thisParameter = (signature as any).thisParameter as ts.Symbol | undefined;
const thisType = checker.getTypeOfSymbolAtLocation(thisParameter!, node.type!);
console.log(thisType); // void

或者,也可以直接从类型中获取。在这种情况下,ts.Typets.TypeReference,因此:

const type = checker.getTypeAtLocation(node.type!) as ts.TypeReference;
const typeArg = type.typeArguments![0];
console.log(typeArg); // void

最新更新