0

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'.
1
  • how do you define constants ? Commented Feb 15, 2020 at 18:50

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.