像那样
enum Response {
@Descriptor("this is No")
No = 0,
@Descriptor("this is Yes")
Yes = 1,
}
Run Code Online (Sandbox Code Playgroud)
如何在打字稿中使用enum中的装饰器,我尝试了这段代码,但它没有用
export function Description(description:string){
return Reflect.metadata(descriptionMetadataKey, description);
}
Run Code Online (Sandbox Code Playgroud)
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,
}
Run Code Online (Sandbox Code Playgroud)
While the descriptions won't be available at runtime, they will show up in editor auto-completion:
如果你真的,真的需要在运行时的文字装饰信息,你可以使用一个类来代替。由于装饰器可以应用于类属性,因此您可以编写一个类,装饰其属性,然后将类的实例用作“枚举”。
function Descriptor(description: string) {
return (target: any, propertyName: string) => {
// process metadata ...
};
}
class ResponsesEnum {
@Descriptor("this is No")
readonly Yes = 1;
@Descriptor("this is No")
readonly No = 2;
}
const Responses = new ResponsesEnum();
Run Code Online (Sandbox Code Playgroud)
在这里尝试。
| 归档时间: |
|
| 查看次数: |
885 次 |
| 最近记录: |