DEV Community

Discussion on: TypeScript's enum + JavaScript's "in" = 👍

Collapse
 
0916dhkim profile image
Danny Kim

Does this mean RobotStatus.damaged === DisposableStatus.damaged ? It is a cool mechanism, but also confusing to me. I prefer using string unions over enums, and one of the reasons is this comparison issue. To me, two enums should never be equal to each other like an int and a string cannot be equal (as in ===). JS is a mess because it allows too many non-trivial comparisons, and TS solves many of its problems. It feels weird to see this type of magic working. I would do something like the following instead:

type RobotStatus = 'ready' | 'damaged' | 'faulty';
const disposableStatus: Set<RobotStatus> = new Set(['damaged', 'faulty']) as const;

function disposeRobot(robot: Robot): void {
  if (disposableStatus.has(robot.status)) {
    // Dispose.
  }
  // Invalid state.
}
Enter fullscreen mode Exit fullscreen mode