如何使用 TypeScript 编译器 API 4.2+(或 ts-morph 10+)从以下内容中提取:
export type A = Record<string,number>
Record
string
& number
Record
也是一个类型别名 最佳答案
由于 TS 4.2 中的行为发生了变化,到目前为止我能想到的最好的事情是遍历 AST 并检查类型别名的类型节点。不过可能有更好的方法...
在 ts-morph 中:
const aTypeAlias = sourceFile.getTypeAliasOrThrow("A");
const typeNode = aTypeAlias.getTypeNodeOrThrow();
if (Node.isTypeReferenceNode(typeNode)) {
// or do typeNode.getType().getTargetType()
const targetType = typeNode.getTypeName().getType();
console.log(targetType.getText()); // Record<K, T>
for (const typeArg of typeNode.getTypeArguments()) {
console.log(typeArg.getText()); // string both times
}
}
使用编译器 API:const typeAliasDecl = sourceFile.statements[0] as ts.TypeAliasDeclaration;
const typeRef = typeAliasDecl.type as ts.TypeReferenceNode;
console.log(checker.typeToString(checker.getTypeAtLocation(typeRef.typeName))); // Record<K, T>
for (const typeArg of typeRef.typeArguments ?? []) {
console.log(checker.typeToString(checker.getTypeAtLocation(typeArg))); // string
}
关于typescript - 如何从引用其他类型别名的类型别名中提取类型参数和类型参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66389805/