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>
Record
string
& number
Record
is also a type aliasSince 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
}