TypeScript Compiler API: How to get type with resolved type arguments?

二次信任 提交于 2021-01-28 08:10:14

问题


I want to merge class declarations in a .dt.s file to generate a cleaner public API. I am stuck on how to make this work with generic type arguments. Let's say I have:

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

export class B1 extends A1<string> {
}

Ideally, I want to turn this into:

export class B1 {
  data?: string;
}

I can get the type of A1 and then copy its members. But how do get a resolved version of A1 that uses string instead of T?

For reference, this is my current code:

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

回答1:


I believe the method you are looking for is TypeChecker#getTypeOfSymbolAtLocation(symbol, node).

The following should get the resolved type of string | undefined:

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


来源:https://stackoverflow.com/questions/63944135/typescript-compiler-api-how-to-get-type-with-resolved-type-arguments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!