1

I have an enum like this that I use as a type

export enum PathDirection {
    ASCENDING="ASCENDING";
    DESCENDING="DESCENDING";
};

In some part of my code, I would like to get the opposite path direction as the one I have. Something like this :

let myVar = PathDirection.ASCENDING;

myVar = !myVar;

Is there any way to overload the logical operator ! to make this happen ?

SnoAke
  • 43
  • 4
  • 1
    No that's not possible, at runtime your `enum` is a `string`. – Matthieu Riegler Nov 22 '22 at 17:34
  • JavaScript has no operator overloading, and TypeScript doesn't like to add runtime functionality like that to JavaScript. Do you want an answer that just says "no, sorry"? Or are you interested in alternatives like abandoning enums in favor of booleans like [this](https://tsplay.dev/wj1RYW)? – jcalz Nov 22 '22 at 18:44
  • Thank you for your answers ! No I wanted it to be a string, but if it's not possible, I'll manage to do it otherwise :) – SnoAke Nov 23 '22 at 14:47

1 Answers1

1

No, this is not possible.

JavaScript does not allow you to overload operators. See the answer to Javascript: operator overloading for more information.

Furthermore, TypeScript does not add such functionality to JavaScript. That would require the compiler to emit different JavaScript for !xxx depending on the compile-time type of xxx, which would run afoul of TypeScript Design Non-Goal #5. See microsoft/TypeScript#5407 for more information.

jcalz
  • 264,269
  • 27
  • 359
  • 360