解析 AST 类型节点结构 –– TypeScript Compiler API

Resolve AST Type Node Structure –– TypeScript Compiler API

假设我们有以下代码:

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

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

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

是否有任何内置机制可以从一系列相互交织的类型 and/or 接口定义中解析最终类型?通过使用类型检查器和类型节点,我找不到任何明显的东西。

如有任何建议,我们将不胜感激!

结构类型没有 public API(请参阅 Type Relationship API issue)。

也就是说,您可以通过执行以下操作获取所有 属性 具有接口类型的名称:

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("---");
}

输出:

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