如何解决如何从引用其他类型别名的类型别名中提取类型参数和类型参数?
如何使用 TypeScript 编译器 API 4.2+(或 ts-morph 10+)从以下内容中提取:
export type A = Record<string,number>
解决方法
由于 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
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。