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

How to extract type arguments and type parameters from a type aliases references other type aliases?

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

export type A = Record<string,number>
  1. 导出类型别名 A 的事实
  2. 是对Record
  3. 的引用
  4. 并通过它 string & number
  5. 并且 Record 也是类型别名
  6. 有两个类型参数,
  7. 得到每个人的names/constraints/defaults。

自从 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
}