有什么办法,我如何检测某个对象是否实现了某个接口?
if(myObj implements IMyInterface) {
//... do something
}
Run Code Online (Sandbox Code Playgroud)
Bor*_*kov 16
没有.
目前,类型仅在开发和编译期间使用.类型信息不会以任何方式转换为已编译的JavaScript代码.
通过编译器生成一些代码,这是可能的.目前,TypeScript团队正在尝试向最终的JavaScript添加尽可能少的代码,例外是'extends'关键字,它为编译的输出添加了一个新方法.
是的.现在,您可以使用TypeScript编译器的增强版本来执行此操作,该编译器允许您知道哪个接口实现了应用程序的每个类.此版本的编译器将所有类型信息存储到运行时,并将这些信息链接到实际构造函数.例如,您可以编写如下内容:
function implementsInterface(object: Object, target: Interface) {
const objClass: Class = object.constructor && object.constructor.getClass();
if (objClass && objClass.implements) {
let found = false;
for (let base of objClass.implements) {
let found = interfaceExtends(base, target);
if (found) {
return true;
}
}
}
return false;
}
// recursive interface inheritance check
function interfaceExtends(i: Interface, target: Interface) {
if (i === target) {
return true;
}
if (i.extends) {
let found = false;
for (let base of i.extends) {
// do a recursive check on base interface...
found = interfaceExtends(base, target);
if (found) {
return true;
}
}
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
您可以在这里找到适合您需求的完整工作示例
| 归档时间: |
|
| 查看次数: |
8295 次 |
| 最近记录: |