Search code examples
typescript

How to use decorators on enum in TypeScript


Like this

enum Response {
    @Descriptor("this is No")
    No = 0,
    @Descriptor("this is Yes")
    Yes = 1,
}

How to use decorators on enum in TypeScript, I tried this code, but it didn't work

export function Description(description:string){
     return Reflect.metadata(descriptionMetadataKey, description);
}

Solution

  • Short answer is, you can't (as of this writing). There are some alternatives though.

    Alternative: Doc Comments

    If you only want to add descriptions to your enum literals, you could use doc comments.

    enum Response {
        /**
         * this is No
         */
        No = 0,
        /**
         * this is Yes
         */
        Yes = 1,
    }
    

    While the descriptions won't be available at runtime, they will show up in editor auto-completion:

    auto-completion example

    Alternative: Enum Class

    If you really, really need the decorated info on the literals at runtime, you could use a class instead. Since decorators can be applied to class properties, you can write a class, decorate its properties and then use an instance of the class as your "enum".

    function Descriptor(description: string) { 
        return (target: any, propertyName: string) => {
            // process metadata ...        
        };
    }
    
    class ResponsesEnum {
        @Descriptor("this is Yes")
        readonly Yes = 1;
        @Descriptor("this is No")
        readonly No = 2;
    }
    const Responses = new ResponsesEnum();
    

    Try it here.