Detect whether object implement interface in TypeScript dynamically

typescript

Solution

Yes, if you use the reflec-ts compiler instead of the standard `tsc` compiler. This 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;
}

You can find a full working example that suits your needs here

Problem

Is there any way, how can I detect whether some object implements some interface? ``` if(myObj implements IMyInterface) { //... do something } ```

Original source

Related problems