首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何从类型别名引用其他类型别名中提取类型参数和类型参数?

如何从类型别名引用其他类型别名中提取类型参数和类型参数?
EN

Stack Overflow用户
提问于 2021-02-27 00:51:34
回答 1查看 196关注 0票数 2

如何使用变形编译器4.2+ (或ts- TypeScript 10+)从以下内容中提取:

代码语言:javascript
复制
export type A = Record

导出类型别名A

是对

并通过它

&

那就是

也是一个类型别名。

使用两个类型参数,

获取每个对象的名称/约束/默认值。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-02-27 23:43:36

由于TS4.2中的行为发生了变化,到目前为止,我能想到的最好的方法就是遍历AST并检查类型别名的类型节点。不过,也许有更好的办法...

在ts变形中:

代码语言:javascript
复制
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

  for (const typeArg of typeNode.getTypeArguments()) {
    console.log(typeArg.getText()); // string both times
  }
}

使用编译器API:

代码语言:javascript
复制
const typeAliasDecl = sourceFile.statements[0] as ts.TypeAliasDeclaration;
const typeRef = typeAliasDecl.type as ts.TypeReferenceNode;

console.log(checker.typeToString(checker.getTypeAtLocation(typeRef.typeName))); // Record

for (const typeArg of typeRef.typeArguments ?? []) {
  console.log(checker.typeToString(checker.getTypeAtLocation(typeArg))); // string
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66389805

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档