[英]TypeScript Compiler API function which can check if a class implements an interface
I wanted to check whether a ClassDeclaration
of a file a.ts
implements an InterfaceDeclaration
from a file b.ts
using Compiler API .我想检查是否一个ClassDeclaration
文件的a.ts
实现了InterfaceDeclaration
从文件b.ts
使用编译器API 。 But I couldn't find a method or a function for it.但是我找不到它的方法或函数。
function isClassImplementInterface(
ts.ClassDeclaration: classDeclaration,
ts.InterfaceDeclaration: interfaceDeclaration
): boolean {
// return true if classDeclaration implements interfaceDeclaration correctly
}
Is there any function for it out of Compiler API? Compiler API 中是否有针对它的功能?
To check if a class directly implements a certain interface you can look at the types of the implements heritage clause.要检查一个类是否直接实现了某个接口,您可以查看 implements 继承子句的类型。
For example:例如:
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;
}
You may want to expand on that to also check if the class declaration has a base class and then check that class' heritage clauses as well.您可能希望对此进行扩展,以检查类声明是否具有基类,然后还检查该类的继承子句。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.