简体   繁体   English

Typescript const枚举问题

[英]Typescript const Enum issue

I have declared the following enum in my Typescript file: 我在我的Typescript文件中声明了以下枚举:

export const enum INPUT_PATTERNS{
    ALL          = ".*",
    ONLY_NUMBERS = "[0-9]*"

}

During compilation, I keep on getting the following error message: 在编译期间,我继续收到以下错误消息:

In 'const' enum declarations member initializer must be constant expression. 在'const'enum声明中,成员初始值设定项必须是常量表达式。

I have initialized the enums with constant values and so I dont understand whats wrong here? 我用常量值初始化了枚举,所以我不明白这里有什么问题?

Secondly, if I remove the const identifier from enum as follows: 其次,如果我从枚举中删除const标识符如下:

export enum INPUT_PATTERNS{
    ALL          = ".*",
    ONLY_NUMBERS = "[0-9]*"

}

then I get the following error: 然后我收到以下错误:

Type '". "' is not assignable to type 'INPUT_PATTERNS'. 键入'“。 ”'不能分配给'INPUT_PATTERNS'。
Type '"[0-9] "' is not assignable to type 'INPUT_PATTERNS'. 类型'“[0-9] ”'不能分配给'INPUT_PATTERNS'类型。

You could do: 你可以这样做:

export enum INPUT_PATTERNS{
    ALL          = <any>".*",
    ONLY_NUMBERS = <any>"[0-9]*" 

}

Enums allow us to define a set of named numeric constants. 枚举允许我们定义一组命名的数字常量。 http://www.typescriptlang.org/docs/handbook/enums.html http://www.typescriptlang.org/docs/handbook/enums.html

You can use a combination of namespace and const variables: 您可以使用命名空间和const变量的组合:

export namespace INPUT_PATTERNS {
    export const ALL = ".*";
    export const ONLY_NUMBERS = "[0-9]*";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM