Search code examples
typescriptenumsoverloadinglogical-operators

Overload logical operator with enum typing in typescript


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 ?


Solution

  • 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.