'How to ensure switch/case includes all enums with TypeScript?

I have 2 enums Color and Shape. The SHAPES_BY_COLOR constant maps the available shapes to the individual colors.

Later, I want to perform different actions based on the selected color and shape by using a simple switch/case statement.

Is there a way that TypeScript "tells me" that a shape is missing or not available 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 to ensure that all cases from color "blue" are included here?
  // 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 "";
  }
};



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source