在 TypeScript 中使用带枚举的 Switch 语句
How to use a Switch statement with Enums in TypeScript
要将 switch 语句与枚举一起使用:
- 创建一个将枚举值作为参数的可重用函数。
- 使用 switch 语句并打开提供的值。
- 从每个分支返回一个特定的值。
enum Sizes { Small, Medium, } function getSize(size: Sizes) { switch (size) { case Sizes.Small: console.log('small'); return 'S'; case Sizes.Medium: console.log('medium'); return 'M'; default: throw new Error(`Non-existent size in switch: ${size}`); } } console.log(getSize(Sizes.Small)); // 👉️ "S" console.log(getSize(Sizes.Medium)); // 👉️ "M"
我们创建了一个可重用的函数,它将枚举值作为参数,在返回其他内容之前打开枚举值。
If you have a
numeric enum
and you try to use a switch statement directly, you might get an error that
“Type X is not compatible to type Y”.
In this scenario, you can convert the enum value to a number when switching on
it.
enum Sizes { Small, Medium, } switch (Number(Sizes.Small)) { case Sizes.Small: console.log('size is S'); break; case Sizes.Medium: console.log('size is M'); break; default: console.log(`non-existent size: ${Sizes.Small}`); break; }
Had we not converted the enum value to a number when switching on it, we would
get an error that the two types are not compatible.
Make sure to always use the break
keyword to avoid a fallthrough switch, which
could run multiple code blocks.
If you’re in a function, you will most likely be using return
instead of
break
.
If you are getting a similar error when working with string enums, you can
convert the value to a string in the switch statement.
enum Sizes { Small = 'S', Medium = 'M', } switch (String(Sizes.Small)) { case Sizes.Small: console.log('size is S'); break; case Sizes.Medium: console.log('size is M'); break; default: console.log(`non-existent size: ${Sizes.Small}`); break; }
如果您运行上面示例中的代码,size is S
消息将记录到控制台。