【问题标题】:TypeScript Compiler API: Get resolved return type of a generic methodTypeScript Compiler API:获取泛型方法的已解析返回类型
【发布时间】:2020-11-13 04:03:15
【问题描述】:

假设我们有一个泛型类或接口:

interface A<T> {
    prop1: T;
    func2(): T;
}

interface B extends A<C> {
}


interface C {
}

我们需要获取B.func2方法的返回类型(不是T而是C)。

here 描述的方式适用于道具,但我不知道如何修改它的方法:

for (const statement of sourceFile.statements) {

    if (!isInterface(statement))
        continue;

    if (!statement.heritageClauses?.length)
        continue;

    for (const heritageClause of statement.heritageClauses) {

        for (const exprWithTypeArgs of heritageClause.types) {
            const baseType = checker.getTypeAtLocation(exprWithTypeArgs);

            for (const propSymbol of baseType.getProperties()) {
                const resolvedType = checker.getTypeOfSymbolAtLocation(propSymbol, exprWithTypeArgs);

                console.log(`${propSymbol.name} has type: ${resolvedType.symbol?.name}`);
                // prints
                // prop1 has type: C
                // func2 has type: func1

                for (const propDeclaration of propSymbol.declarations) {
                    if (!isSignatureDeclaration(propDeclaration))
                        continue;

                    const signature = checker.getSignatureFromDeclaration(propDeclaration);
                    const returnTypeSymbol = checker.getReturnTypeOfSignature(signature)?.symbol;
                    const resolvedReturnType = checker.getTypeOfSymbolAtLocation(returnTypeSymbol, exprWithTypeArgs);

                    console.log(`${propSymbol.name} return type: ${resolvedReturnType.symbol?.name}`);
                    // prints
                    // func2 return type: undefined
                }
            }
        }
    }
}

获取方法返回类型的正确方法是什么?

【问题讨论】:

    标签: typescript-compiler-api


    【解决方案1】:

    TypeChecker#getSignaturesOfType 方法允许获取类型的签名。

    const bDecl = sourceFile.statements[1]; // obviously, improve this
    const bType = typeChecker.getTypeAtLocation(bDecl);
    const func2Symbol = bType.getProperty("func2")!;
    const func2Type = typeChecker.getTypeOfSymbolAtLocation(func2Symbol, func2Symbol.valueDeclaration);
    const func2Signature = checker.getSignaturesOfType(func2Type, ts.SignatureKind.Call)[0];
    
    checker.typeToString(func2Signature.getReturnType()); // C
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-11
      • 1970-01-01
      • 1970-01-01
      • 2019-05-04
      • 2016-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多