I have some code:
enum Color {
Red,
Green,
Blue
}
function getColorName(c: Color): string {
switch(c) {
case Color.Red:
In really simple cases when you just need to return some string by enum value it's easier (IMHO) to use some constant to store dictionary of results instead of using switch. For example:
enum Color {
Red,
Green,
Blue
}
function getColorName(c: Color): string {
const colorNames: Record = {
[Color.Red]: `I'm red`,
[Color.Green]: `I'm green`,
[Color.Blue]: `I'm blue, dabudi dabudai`,
}
return colorNames[c] || ''
}
So here you will have to mention every enum value in constant, otherwise you get an error like, for example, if Blue is missing:
TS2741: Property 'Blue' is missing in type '{ [Color.Red]: string; [Color.Green]: string;' but required in type 'Record'.
However it's often not the case and then it's really better to throw an error just like Ryan Cavanaugh proposed.
Also I was a bit upset when found that this won't work also:
function getColorName(c: Color): string {
switch(c) {
case Color.Red:
return 'red';
case Color.Green:
return 'green';
}
return '' as never // I had some hope that it rises a type error, but it doesn't :)
}