Resolve AST Type Node Structure –– TypeScript Compiler API

Viewed 484

Let's say we have the following code:

interface X<Y = any> {
  y: Y;
}

interface Z extends X<"why?"> {
  abc: "ABC";
}

/**
 *
 * Structurally, the `Z` type is...
 *
 * {
 *   y: "why?";
 *   abc: "ABC";
 * }
 *
 */

Is there any built-in mechanism for resolving the final type from a series of intertwined type and/or interface definitions? I can't find anything obvious from playing around with a typechecker and Type nodes.

Any advice would be greatly appreciated!

1 Answers

There's no public API for structural typing (see the Type Relationship API issue).

That said, you can get all the property names with types of the interface by doing the following:

const interfaceZDecl = sourceFile.statements[1] as ts.InterfaceDeclaration;
const type = checker.getTypeAtLocation(interfaceZDecl.name);

for (const prop of type.getProperties()) {
    console.log(`Name: ${prop.getName()}`);
    const propType = checker.getTypeOfSymbolAtLocation(prop, prop.valueDeclaration);
    console.log(`Type: ${checker.typeToString(propType)}`);
    console.log("---");
}

Outputs:

Name: abc
Type: "ABC"
---
Name: y
Type: "why?"
---
Related