typescript 打字稿枚举开关不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27747437/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Typescript enum switch not working
提问by Mantzas
i have the following enum
我有以下枚举
enum EditMode {
View = 0,
Edit = 1,
Delete = 2
}
Let's assume i have a variable of the enum type
假设我有一个枚举类型的变量
var editMode = EditMode.Edit;
Why does the following code not work (goes straight to default)?
为什么以下代码不起作用(直接进入默认值)?
switch (editMode) {
case EditMode.Delete:
...
break;
case EditMode.Edit:
...
break;
default:
...
break;
}
采纳答案by Mantzas
i have found why i does happen. somewhere in the code there is a activation function (i am using durandal) which passes this enum as a string (the function has the parameter marked as a enum but still it is a string). this is why my switch statement fails. i simply converted the value to a number and now everything works as expected. thanks anyways
我找到了为什么我会发生。代码中的某处有一个激活函数(我正在使用 durandal),它将此枚举作为字符串传递(该函数将参数标记为枚举,但它仍然是一个字符串)。这就是我的 switch 语句失败的原因。我只是将值转换为数字,现在一切都按预期工作。不管怎么说,多谢拉
回答by Shaul Behr
I also had this problem. Easy way to get around it: add a +
sign before your variable in the switch, i.e.
我也有这个问题。绕过它的简单方法:+
在 switch 中的变量前添加一个符号,即
switch (+editMode) {
case EditMode.Delete:
...
break;
case EditMode.Edit:
...
break;
default:
...
break;
}
回答by acat
The issue here has to do with typescript's (numeric) literal types. When you do this assignment:
这里的问题与打字稿的(数字)文字类型有关。当你做这个任务时:
var editMode = EditMode.Edit
TypeScript evaluates the type as:
TypeScript 将类型评估为:
var editMode: 1 = EditMode.Edit
Now, when you compare a value that typescript knows mustbe 1
(EditMode.Edit
) to a value that it knows mustbe 0
(EditMode.View
), it sees all this as a type-safety violation. If the variable editMode
weren't an enum
, typescript would merely complain, but since it's an enum
, which doesn't really exist in javascript, typescript gets to control the transpilation in such a way that it actually throws an error.
So you have 2 options. So you can either coerce editMode
to be a number
or to be an EditMode
(i.e. any of the values EditMode
is permitted to be, not just the one assigned to editMode
the variable).
Personally, I prefer to coerce it to be an EditMode
, because it feels more type-safe.
To go the number route, you can do the following, which was previously mentioned:
现在,当您将 typescript 知道必须是1
( EditMode.Edit
) 的值与它知道必须是0
( EditMode.View
)的值进行比较时,它会将所有这些都视为违反类型安全。如果变量editMode
不是 an enum
,typescript 只会抱怨,但由于它是 an enum
,在 javascript 中并不真正存在,因此 typescript 会以实际上抛出错误的方式控制转译。
所以你有2个选择。因此,您可以强制editMode
成为 anumber
或成为 an EditMode
(即EditMode
允许任何值,而不仅仅是分配给editMode
变量的值)。
就个人而言,我更愿意将其强制为EditMode
,因为它感觉更类型安全。
要走号码路线,您可以执行以下操作,这是前面提到的:
switch(+editMode)
To go the EditMode
route (which I recommend), you can pass it to a function as was mentioned, but sometimes it's a little cleaner to not write a function. If that's the case here, then you can again coerce the type in the switch
statement:
要走这EditMode
条路线(我推荐),您可以将其传递给前面提到的函数,但有时不编写函数会更简洁一些。如果是这种情况,那么您可以再次强制switch
语句中的类型:
switch(editMode as EditMode)
Do whichever you prefer, but I just like the clarity of explicitly saying "this variable is being treated as an EditMode
" as opposed to "this variable is supposed to actually be a number
, not an Enum
".
做你喜欢的任何事情,但我只是喜欢明确地说“这个变量被视为EditMode
”而不是“这个变量实际上应该是一个number
,而不是一个Enum
”。
回答by Rashid Iqbal
TypeScript version 3.7.5
打字稿版本3.7.5
this code worked for me
这段代码对我有用
enum Seasons {
Winter,
Spring,
Summer,
Autum
}
switch (+Seasons.Winter) {
case Seasons.Winter:
console.log('weather is cold');
break;
case Seasons.Spring:
console.log('weather is spring');
break;
case Seasons.Summer:
console.log('weather is summer');
break;
default:
break;
}
or you can declare a constant and use as param for switch statement
或者您可以声明一个常量并用作 switch 语句的参数
const season: Seasons = Seasons.Winter
switch (+season) {
case Seasons.Winter:
console.log('weather is cold');
break;
case Seasons.Spring:
console.log('weather is spring');
break;
case Seasons.Summer:
console.log('weather is summer');
break;
default:
break;
}
回答by ohsully
In case somebody else ends up here and the above options don't seem to be the issue, double-check that all of your switch statements are breaking/returning! The Typescript compiler is smart enough to see that if your case
cascades through to another one, the value you're comparing on may never hit the case you expect.
如果其他人在这里结束并且上述选项似乎不是问题,请仔细检查您的所有 switch 语句是否中断/返回!Typescript 编译器足够聪明,可以看到如果您case
级联到另一个,您正在比较的值可能永远不会达到您期望的情况。
let handlerName;
switch(method){
case 'create':
handlerName = 'createHandler';
break;
case 'update';
handlerName = 'updateHandler';
// Here is where the forgotten break would go
default:
throw new Error('Unrecognized Method');
}
switch(handlerName){
case 'createHandler':
...
break;
case 'updateHandler':
// You will see an error on this case because
// the compiler knows that execution will never
// arrive here with handler === 'updateHandler'
default:
throw new Error('Unrecognized Handler');
}
回答by java-addict301
Change your EditMode enum definition to:
将您的 EditMode 枚举定义更改为:
enum EditMode {
View = "View",
Edit = "Edit",
Delete = "Delete"
}
Typescript 3.6.3
打字稿 3.6.3
回答by user1067920
If you use the switch
expression in a function with typed parameter, this works as expected.
如果您switch
在带有类型参数的函数中使用表达式,这将按预期工作。
Example:
例子:
enum EditMode {
View,
Edit,
Delete,
}
function testSwitch(editMode: EditMode) {
switch(editMode) {
case EditMode.Delete:
console.log("delete");
break;
case EditMode.Edit:
console.log("edit");
break;
default:
console.log("default");
break;
}
}
testSwitch(EditMode.Edit)
will compile and output edit
将编译并输出 edit
回答by Gerard
In my case I had the switch inside a condition, which was coercing the enum into a value:
在我的情况下,我在一个条件中设置了开关,它将枚举强制转换为一个值:
enum A {
VAL_A,
VAL_B,
VAL_C
}
interface ia {
maybe?: A
}
const o: ia = {maybe: 0}
if(o.maybe){ //<-- o.maybe is not falsey (thus, is not 0)
switch(o.maybe) {
case A.VAL_A: //<-- Error! we know that o.maybe is not 0. Its VAL_B | VAL_C
break;
}
}
回答by ldobson
If the enum is defined in a separate typescript file, ensure it's marked with "export" and that you import it correctly at the top of the typescript file you're referencing it in.
如果枚举是在单独的打字稿文件中定义的,请确保它标有“导出”,并且您在引用它的打字稿文件的顶部正确导入它。
回答by Anton Aksiuta
Declare your enum using const
:
使用const
以下方法声明您的枚举:
const enum EditMode {
View = 0,
Edit = 1,
Delete = 2
}