In the case of having a constant enum like:
enum Color {
RED,
GREEN,
BLUE,
}
A common approach is to create a helper function accompanied by a switch statement, as shown below:
function assertNever(x: never): never {
throw new Error(`Unexpected object: ${x}`)
}
function toString (key: Color): string {
switch (key) {
case Color.RED: return 'Red'
case Color.GREEN: return 'Green'
case Color.BLUE: return 'Blue'
default: return assertNever(key)
}
}
This design makes it necessary to update the toString
implementation whenever changes are made to the Color
enum.
However, when looking at the reverse scenario:
function fromString (key: string): Color {
switch (key) {
case 'Red': return Color.RED
case 'Green': return Color.GREEN
case 'Blue': return Color.BLUE
default: throw new Error(`${key} is not a Color`)
}
}
It becomes evident that keeping the fromString
function updated with any modifications to the Color
enum could be challenging.
Is there a method to guarantee that every Color
type has a corresponding path in the function? How can we ensure that the function's output range remains within the boundaries of the Color
enum?