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);
}
Short answer is, you can't (as of this writing). There are some alternatives though.
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:
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.
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With