请问如何用 typescript 实现下面的同样效果的 C# switch 表达式
public class Program
{
public static void Main()
{
int dayOfWeek = 2;
string day = dayOfWeek switch
{
1 => "Monday",
2 => "Tuesday",
3 => "Wednesday",
_ => "Another day"
};
Console.WriteLine(day);
}
}
采用了 How to assign a variable to switch statement result 这篇博文中的方法
const dayOfWeek: number = 2;
const day = (function () {
switch (dayOfWeek) {
case 1:
return { one: 1 };
case 2:
return "Tuesday";
case 3:
return "Wednesday";
default:
return "Another day"
}
})();
console.log(day);
deepseek 给出的基于 Record 的一种实现
const FRUIT_COLORS: Record<Fruit, string> = {
apple: "red",
banana: "yellow",
orange: "orange",
grape: "purple"
};
const color = FRUIT_COLORS[fruit]; // Safer and more concise
说个稍微跑题的,js或ts里用对象键值对直接取值也是比较常见的。
如果非要约束,那么可以考虑enum:
enum EWeekday {
Monday = 1,
Tuesday,
Wednesday
//...
}
type EWeekdayMap = {
[k in EWeekday]?: string
}
const weekdayMap: EWeekdayMap = {
[EWeekday.Monday]: "Monday",
// ...
}
const getWeekdayExpression = (d: EWeekday, defaultValue = "???") => weekdayMap[d] || defaultValue
console.log(getWeekdayExpression(1))
实现场景中 "Monday"
是一个包含变量值的字符串拼接