mkkekkonen
mkkekkonen

Reputation: 1774

Switch statement throws error in TypeScript when attempting to handle enum values

I'm using the following while and switch-case loops. I'm trying to handle all the different enum values in the constants.Sides enum.

// EDIT Constants is imported at the top of the file.

import * as constants from '../constants'

// ... other code not included

let crossedSide: constants.Sides | undefined;
let loopGuard = 0;

while ((crossedSide = this.hasCrossedBorder()) && loopGuard < 2) {
  loopGuard += 1;

  switch (crossedSide) {
    case constants.Sides.TOP: { // THE ERROR HAPPENS HERE
      this.velocity.y = -this.velocity.y;
      break;
    }
    case constants.Sides.RIGHT: {
      this.velocity.x = -this.velocity.x;
      break;
    }
    case constants.Sides.BOTTOM: {
      this.velocity.y = -this.velocity.y;
      break;
    }
    case constants.Sides.LEFT: {
      this.velocity.x = -this.velocity.x;
      break;
    }
    default:
      break;
  }
}

The enum is defined in constants/index.ts as follows:

export enum Sides {
  TOP,
  RIGHT,
  BOTTOM,
  LEFT,
}

However, an error is thrown at the constants.Sides.TOP switch-case option:

Type 'Sides.TOP' is not comparable to type 'Sides.RIGHT | Sides.BOTTOM | Sides.LEFT'.

Upvotes: 0

Views: 532

Answers (1)

mkkekkonen
mkkekkonen

Reputation: 1774

The problem lies in TypeScript handling the first enum value, i.e. TOP, as 0 i.e. falsy. This is why the while condition returns only the remaining three truthy enum values: RIGHT, BOTTOM and LEFT.

The issue is fixed by adding another value to the enumeration like so:

export enum Sides {
  NONE = 0,
  TOP,
  RIGHT,
  BOTTOM,
  LEFT,
}

This way also the TOP value will be truthy.

Upvotes: 1

Related Questions