我在 TypeScript 枚举中有这个:
export enum LMXLockRequestError {
MaxRetries = 'bad_args',
BadArgumentsError = 'bad_args',
}
这似乎不会导致编译错误。 它转换为:
var LMXLockRequestError;
(function (LMXLockRequestError) {
LMXLockRequestError["MaxRetries"] = "bad_args";
LMXLockRequestError["BadArgumentsError"] = "bad_args";
})(LMXLockRequestError = exports.LMXLockRequestError || (exports.LMXLockRequestError = {}));
如果我要用它来做:
if(v === LMXLockRequestError.MaxRetries){
}
如果 v 是 'bad_args',它将同时匹配 MaxRetries 和 BadArgumentsError。
这是应该发生的吗?或者我应该在 Github 上提交 TypeScript 问题吗?
对我来说,枚举应该有不同的键,但不一定有不同的值?如果有一种方法可以告诉枚举它必须具有不同的值,那就太好了。
最佳答案
关于 TS ENUM 规范:
Enums allow us to define a set of named constants. Using enums can make it easier to document intent, or create a set of distinct cases. TypeScript provides both numeric and string-based enums.
没有任何关于它应该是 uniq 的东西,所以可能这种行为是好的。
更新: 关于 ENUM 和“错误”还有另一件有趣的事情:
Enum value incrementation does not consider previously defined values, nor does the compiler throws an error on duplicate values.
Which means you can end up with potential bugs:
enum Color {Red = 3, Green = 2, Blue};
Color.Red == Color.Blue; //true
关于typescript - TS 枚举中的重复字符串值不会导致编译错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51170387/