Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use decorators on enum in TypeScript

Tags:

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);
}
like image 814
cyhone Avatar asked Sep 06 '18 06:09

cyhone


2 Answers

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.

like image 85
Fabian Lauer Avatar answered Sep 28 '22 01:09

Fabian Lauer


You can't. Where you can use decorators in TypeScript:

Class Decorators

@sealed
class Greeter {}

Method Decorators

class Greeter {
    @enumerable(false)
    greet() {
        return "Hello, " + this.greeting;
    }
}

Accessor Decorators

class Point {
    private _x: number;

    @configurable(false)
    get x() { return this._x; }
}

Property Decorators

class Greeter {
    @format("Hello, %s")
    greeting: string;
}

Parameter Decorators

class Greeter {
    greet(@required name: string) {
        return "Hello " + name + ", " + this.greeting;
    }
}
like image 45
Buggy Avatar answered Sep 28 '22 02:09

Buggy