Interface type check with Typescript

前端 未结 17 1293
灰色年华
灰色年华 2020-11-22 14:09

This question is the direct analogon to Class type check with TypeScript

I need to find out at runtime if a variable of type any implements an interface. Here\'s my

17条回答
  •  误落风尘
    2020-11-22 14:40

    It's now possible, I just released an enhanced version of the TypeScript compiler that provides full reflection capabilities. You can instantiate classes from their metadata objects, retrieve metadata from class constructors and inspect interface/classes at runtime. You can check it out here

    Usage example:

    In one of your typescript files, create an interface and a class that implements it like the following:

    interface MyInterface {
        doSomething(what: string): number;
    }
    
    class MyClass implements MyInterface {
        counter = 0;
    
        doSomething(what: string): number {
            console.log('Doing ' + what);
            return this.counter++;
        }
    }
    

    now let's print some the list of implemented interfaces.

    for (let classInterface of MyClass.getClass().implements) {
        console.log('Implemented interface: ' + classInterface.name)
    }
    

    compile with reflec-ts and launch it:

    $ node main.js
    Implemented interface: MyInterface
    Member name: counter - member kind: number
    Member name: doSomething - member kind: function
    

    See reflection.d.ts for Interface meta-type details.

    UPDATE: You can find a full working example here

提交回复
热议问题