如何在打字稿中使用enum中的装饰器

cyh*_*one 9 typescript

像那样

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)

Fab*_*uer 6

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,
}
Run Code Online (Sandbox Code Playgroud)

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

自动补全示例

Alternative: Enum Class

如果你真的真的需要在运行时的文字装饰信息,你可以使用一个类来代替。由于装饰器可以应用于类属性,因此您可以编写一个类,装饰其属性,然后将类的实例用作“枚举”。

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)

在这里尝试。

  • Enum 类在一个非常重要的方面存在不足:它不能用作变量、参数等的类型。类类型仅充当枚举值的容器(和命名空间),但它不代表这些值的类型值本身,就像真正的枚举一样。为此,在上面的示例中,您可能需要定义一个类型别名,例如:`type ResponsesEnumType = number;` (2认同)