【问题标题】:Resolve AST Type Node Structure –– TypeScript Compiler API解析 AST 类型节点结构 –– TypeScript Compiler API
【发布时间】:2020-08-03 19:32:48
【问题描述】:

假设我们有以下代码:

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

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

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

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

任何建议将不胜感激!

【问题讨论】:

  • 我不确定您的用例是什么,您到底需要做什么?对象的完整形状在编译时是已知的,您无需为此做任何特别的事情。如果您在谈论运行时,那是一个完全不同(而且更难)的问题
  • @bugs 不正确:我不想要运行时的形状。我想要它在编译时。但我不想自己遍历并将其拼接在一起,因为 TS 团队可能已经实现了这一点(当然是为了结构类型检查)。

标签: typescript interface abstract-syntax-tree typescript-compiler-api


【解决方案1】:

没有用于结构类型的公共 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?"
---

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-04
    • 2021-02-21
    • 1970-01-01
    • 1970-01-01
    • 2020-05-31
    • 1970-01-01
    • 1970-01-01
    • 2021-05-12
    相关资源
    最近更新 更多