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

Viewed 427

How would one use the TypeScript compiler API 4.2+ (or ts-morph 10+) to extract from the following:

export type A = Record<string,number>
  1. The fact that exported type alias A
  2. is a reference to Record
  3. and passes it string & number
  4. and that Record is also a type alias
  5. with two type parameters,
  6. getting each one's names/constraints/defaults.
1 Answers

Since the behaviour change in TS 4.2, the best thing I can figure out so far is to traverse the AST and inspect the type node of the type alias. There might be a better way though...

In 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
  }
}

With the compiler 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
}
Related