Search code examples
typescriptbooleanvariable-assignmentxor

How do I toggle a boolean in Typescript?


In Javascript (and many other languages), we can just do this:

arrayOfObjects[i].propertyAlsoArray[j] ^= true;

Typescript disallows logical ^, & and | operators. This is a safety feature, so I'd have to do it like this:

arrayOfObjects[i].propertyAlsoArray[j] = !arrayOfObjects[i].propertyAlsoArray[j];

Is there a shorter way that avoids the repetition?


Solution

  • You can't do that in javascript as well:

    let bool = true;
    console.log(bool == true); // true
    console.log(bool === true); // true
    
    bool ^= true;
    console.log(bool == false); // true
    console.log(bool === false); // false
    

    As you can see, the value after the "toggle" isn't a false, it's a 0.
    That's why the compiler complains about it, because you're changing the type of your variable from boolean to number.

    If you don't mind this change in types then you can do something like:

    function toggle(arr: { propertyAlsoArray: number[] }[], i: number, j: number) {
        arr[i].propertyAlsoArray[j] ^= 1;
    }
    
    let arr: { propertyAlsoArray: (boolean | number)[] }[];
    toggle(arr as { propertyAlsoArray: number[] }[], 1, 1);
    

    But what you have now with != is probably the best approach.