如何在 TypeScript 中使用带枚举的 Switch 语句
要将 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"
我们创建了一个可重用的函数,它将枚举值作为参数,在返回其他内容之前打开枚举值。
默认情况是一个实现问题。 在示例中,我们抛出一个错误以指示发生了意外状态 – 传入的值不存在于枚举中。
如果我们有一个数字枚举并且我们尝试直接使用 switch 语句,我们可能会收到“Type X is not compatible to type Y”的错误。
在这种情况下,我们可以在打开时将枚举值转换为数字。
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;
}
如果我们在打开它时没有将枚举值转换为数字,我们会收到两种类型不兼容的错误。
确保始终使用 break
关键字来避免可能运行多个代码块的 fallthrough switch。
如果你在一个函数中,你很可能会使用 return
而不是 break
。
如果我们在使用字符串枚举时遇到类似的错误,我们可以在 switch
语句中将该值转换为字符串。
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
的消息将打印到控制台
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。