【问题标题】:TypeScript Compiler API function which can check if a class implements an interfaceTypeScript Compiler API 函数可以检查一个类是否实现了一个接口
【发布时间】:2019-12-30 05:07:47
【问题描述】:

我想检查文件a.tsClassDeclaration 是否使用Compiler API 从文件b.ts 中实现InterfaceDeclaration。但我找不到它的方法或函数。

function isClassImplementInterface(
  ts.ClassDeclaration: classDeclaration,
  ts.InterfaceDeclaration: interfaceDeclaration
): boolean {
  // return true if classDeclaration implements interfaceDeclaration correctly
}

Compiler API 有什么功能吗?

【问题讨论】:

  • 获取类的类型和接口声明后就可以使用checker.isTypeAssignableTo了。
  • @TitianCernicova-Dragomir 这是内部 API,因此无法使用。请参阅 GitHub 问题 here
  • @DavidSherret Wops,我的错,我认为这是公共 api 的一部分

标签: typescript typescript-compiler-api


【解决方案1】:

要检查一个类是否直接实现了某个接口,您可以查看 implements Heritage 子句的类型。

例如:

function doesClassDirectlyImplementInterface(
    classDec: ts.ClassDeclaration,
    interfaceDec: ts.InterfaceDeclaration,
    typeChecker: ts.TypeChecker
) {
    const implementsClause = classDec.heritageClauses
        ?.find(c => c.token === ts.SyntaxKind.ImplementsKeyword);

    for (const clauseTypeNode of implementsClause?.types ?? []) {
        const clauseType = typeChecker.getTypeAtLocation(clauseTypeNode);
        if (clauseType.getSymbol()?.declarations.some(d => d === interfaceDec))
            return true;
    }

    return false;
}

您可能希望对此进行扩展,以检查类声明是否具有基类,然后还要检查该类的继承子句。

【讨论】:

  • 非常感谢,上面的代码会很有帮助。我将尝试根据您的指南制作实用程序代码。谢谢 ! :D
猜你喜欢
  • 2016-09-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-16
  • 2012-05-29
  • 2014-09-02
相关资源
最近更新 更多