【问题标题】:TypeScript Compiler API: Accessing resolved type of 'this' parameterTypeScript Compiler API:访问“this”参数的解析类型
【发布时间】:2019-05-04 21:14:52
【问题描述】:

使用编译器 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”解析为“无效”。使用调试器进行跟踪时,我可以看到签名有一个名为“thisParameter”的成员,它似乎有我需要的东西。但这并没有通过界面公开公开,所以我不能真正依赖它。有没有办法正确访问类型?

【问题讨论】:

    标签: typescript typescript-compiler-api


    【解决方案1】:

    要从签名中获取 this 参数类型,您似乎需要访问内部 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
    

    【讨论】:

    • 谢谢!但是此解决方案假定声明将始终使用我的示例界面。我需要一个适用于任何签名的通用解决方案。
    • @tomb 更新以显示从签名中获取它。 thisParameter 属性未公开,但看起来您需要访问它。
    • 这就是我害怕的——感谢您的确认
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-12
    • 1970-01-01
    • 2017-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多