Search code examples
typescriptaureliababeljstypescript1.5ecmascript-2016

Using a Decorator to get list of implemented interfaces


Do you know if it is possible to get the array of interfaces implemented by a class using a decorator:

interface IWarrior {
  // ...
}

interface INinja {
  // ...
}

So If I do something like:

@somedecorator
class Ninja implements INinja, IWarrior {
 // ...
}

At run-time Ninja will have an annotation which contains ["INinja", "IWarrior"] ?

Thanks


Solution

  • Currently, types are used only during development and compile time. The type information is not translated in any way to the compiled JavaScript code. But you however can pass the list of strings to the decorator parameter like this:

    interface IWarrior {
      // ...
    }
    
    interface INinja {
      // ...
    }
    
    
    interface Function {
        interfacesList: string[];
    }
    
    @interfaces(["INinja", "IWarrior"])
    class Ninja implements INinja, IWarrior {
    
    }
    
    function interfaces(list: string[]) {
        return (target: any) => {
            target.interfacesList = list; 
            return target;
        }
    }
    
    console.log(Ninja.interfacesList);