TS 枚举中的重复字符串值不会导致编译错误?
Duplicate string values in TS enum does not cause compilation error?
我在 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 和 'bugs' 还有一个有趣的事情:
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
要添加您可能会遇到的实际问题(请记住,在运行时它是使用的值):
enum Toto {
A = "a",
B = "a"
}
const a = Toto.B;
switch (a) {
case Toto.A:
console.log("1");
break;
case Toto.B:
console.log("2");
}
无法进入case Toto.B case。如果打字稿不允许重复的名字,那会很方便。
同样的行为发生在 c# 中:
void Main() {
var blue = Color.Blue;
blue.Dump(); // Red
}
enum Color {
Red = 3,
Green = 2,
Blue
}
我在 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 和 'bugs' 还有一个有趣的事情:
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
要添加您可能会遇到的实际问题(请记住,在运行时它是使用的值):
enum Toto {
A = "a",
B = "a"
}
const a = Toto.B;
switch (a) {
case Toto.A:
console.log("1");
break;
case Toto.B:
console.log("2");
}
无法进入case Toto.B case。如果打字稿不允许重复的名字,那会很方便。
同样的行为发生在 c# 中:
void Main() {
var blue = Color.Blue;
blue.Dump(); // Red
}
enum Color {
Red = 3,
Green = 2,
Blue
}