如何获取数组的已解析类型参数(tsc 编译器 API)

How to get a array's resolved type argument (tsc compiler API)

我已经看到了this other question,但是虽然名称相似,但问题确实不同,因为他们正在尝试获取属性的类型,这发生了与泛型类型参数相同,但我试图获取实际解析的类型参数,因为我想获取 Array<T> 的类型 T,但没有 属性类型 T 内的数组类型。

所以我有这样的功能:

import ts from 'typescript'

function convertType(tc: ts.TypeChecker, type: ts.Type) {
    if (type.symbol.name === 'Array') {
        debugger;
        // How do I get the resolved type of T?
    }
    else {
        //...
    }
}

我注意到,如果我调试函数并将鼠标悬停在 type 上,它将有一个名为 resolvedTypeArguments 的 属性,它具有我需要的确切类型。所以我可以做 (type as any).resolvedTypeArguments,但那会很麻烦,我想知道是否有官方方法可以做到这一点。

我猜我必须使用 is... 函数之一将类型转换为具有 resolvedTypeArguments 属性 的类型,但没有提及“resolvedTypeArguments” ”整个“typescript.d.ts”文件中的任何位置,因此我似乎根本不应该访问该成员。

您需要获取第一个类型参数的类型:

const params = checker.getTypeArguments(type);
console.log(checker.typeToString(params[0])); // T