【问题标题】:TypeScript Compiler API: How to get type with resolved type arguments?TypeScript Compiler API:如何使用已解析的类型参数获取类型?
【发布时间】:2020-09-18 02:51:52
【问题描述】:

我想在 .dt.s 文件中合并类声明以生成更简洁的公共 API。我坚持如何使用泛型类型参数进行这项工作。假设我有:

class A1<T> { // Non-exported class I want to hide
  data?: T;
}

export class B1 extends A1<string> {
}

理想情况下,我想把它变成:

export class B1 {
  data?: string;
}

我可以得到A1的类型,然后复制它的成员。但是如何获得使用string 而不是TA1 的解析版本?

作为参考,这是我当前的代码:

for (const heritageClause of node.heritageClauses) {
  for (const type of heritageClause.types) {
    if (isExported(type.modifiers)) {
      exportedTypes.push(type);
    } else {
      const privateType = typeChecker.getTypeAtLocation(type);
      if (privateType?.symbol?.members) {
        privateType.symbol.members.forEach((definition, memberName) => {
          if (!currentMembers || !currentMembers.has(memberName)) {
            additionalMembers.push(...definition.declarations);
           }
         }
      });
    }
  }
}

【问题讨论】:

    标签: typescript-compiler-api


    【解决方案1】:

    我相信您正在寻找的方法是TypeChecker#getTypeOfSymbolAtLocation(symbol, node)

    以下应该得到string | undefined的解析类型:

    // by the way, recommend renaming `type` to `typeNode` to avoid confusion
    typeChecker.getTypeOfSymbolAtLocation(privateType.getProperties()[0], type);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-04
      • 2021-05-12
      • 1970-01-01
      • 2017-12-30
      • 1970-01-01
      • 2020-06-21
      • 1970-01-01
      • 2021-07-10
      相关资源
      最近更新 更多