typescript - TypeScript Compiler API 函数可以检查一个类是否实现了一个接口
问题描述
我想检查文件的 a 是否使用Compiler API从ClassDeclaration
文件中a.ts
实现。但我找不到它的方法或函数。InterfaceDeclaration
b.ts
function isClassImplementInterface(
ts.ClassDeclaration: classDeclaration,
ts.InterfaceDeclaration: interfaceDeclaration
): boolean {
// return true if classDeclaration implements interfaceDeclaration correctly
}
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;
}
您可能希望对此进行扩展以检查类声明是否具有基类,然后还要检查该类的继承条款。
推荐阅读
- c++ - Cmake用target_compile_definitions替换add_compile_definitions
- html - 滚动通过 iframe 元素时,滚动捕捉不起作用或跳到底部?
- mongodb - Kafka Connect - MongoDB 源连接器 - 管道不工作
- python - 从 Google 聊天组获取聊天消息
- azure - 在注册流程中使用 azure ad b2b 将来宾用户添加到组
- typescript - Adonis V5 Lucid - 条件查询
- c++ - 在 C++ 中的 unordered_map 中排序
- webgl - 为什么 iOS 15 上的 safari 对着色器属性名称很挑剔
- python - 估计两个二维点云之间的旋转
- javascript - Vue连接到firebase - 未捕获的FirebaseError:firebase.initilializeApp中未提供“projectId”