检测对象是否动态实现TypeScript中的接口 [英] Detect whether object implement interface in TypeScript dynamically

查看:25
本文介绍了检测对象是否动态实现TypeScript中的接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么办法,我如何检测某个对象是否实现了某个接口?

Is there any way, how can I detect whether some object implements some interface?

if(myObj implements IMyInterface) {
    //... do something
}

推荐答案

.现在,您可以使用增强版的 TypeScript 编译器来执行此操作,该编译器允许您知道哪个接口实现了应用程序的每个类.这个版本的编译器存储所有类型信息直到运行时,并将这些信息链接到实际的构造函数.例如,您可以编写如下内容:

Yes. Now you can do this, using an enhanced version of the TypeScript compiler that allows you to know which interface implements each class of your application. This version of the compiler stores all types information until runtime, and links these information to actual constructors. For example, you can write something like the following:

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

您可以在此处找到适合您需求的完整工作示例

这篇关于检测对象是否动态实现TypeScript中的接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆