I have 2 enums Color
and Shape
. The constant SHAPES_BY_COLOR
connects shapes with different colors.
In the future, I aim to execute specific actions depending on the selected color and shape using a switch/case statement.
Is there a way for TypeScript to notify me if a particular shape is missing or unavailable for the current color?
enum Color {
blue = "blue",
green = "green",
red = "red",
orange = "orange"
}
enum Shape {
star = "star",
rectangle = "rectangle",
ellipse = "ellipse",
triangle = "triangle",
diamond = "diamond",
}
const SHAPES_BY_COLOR: Record<Color, Shape[]> = {
[Color.blue]: [
Shape.triangle,
Shape.diamond,
],
[Color.green]: [
Shape.star,
Shape.triangle,
Shape.diamond,
],
[Color.red]: [
Shape.ellipse,
Shape.triangle,
],
[Color.orange]: [
Shape.star,
Shape.triangle,
Shape.diamond,
]
}
const getResultForColorBlue = (shape: Shape) => {
// QUESTION: How do we make sure all cases from color "blue" are covered here?
// Can we get a subset of the `Shape` enum from SHAPES_BY_COLOR[Color.Blue]?
switch (shape) {
case Shape.triangle:
return "";
// Show TS error -> Missing shape "Shape.diamond"
case Shape.star: // Show TS error -> Option not available for Color.blue
return "";
}
};