如何使用 TypeScript 编译器 API 4.2+(或 ts-morph 10+)从以下内容中提取:
export type A = Record<string,number>
Record
string
& number
Record
也是一个类型别名答案 0 :(得分:1)
由于 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
}