首页 > 解决方案 > TypeScript Compiler API 函数可以检查一个类是否实现了一个接口

问题描述

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

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

Compiler API 有什么功能吗?

标签: typescripttypescript-compiler-api

解决方案


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

例如:

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

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


推荐阅读