Search code examples
typescriptlinttslintbitwise-or

TSLint not recognizing proper bitwise operators


Sadly, this valid code is considered negligent by the default setting of TSLint:

export const NO_FLAG: number = 0x0000;
export const DESTROY_FLAG: number = 0x0001;
export const NULL_FLAG: number = 0x0100;
export const START_FLAG: number = 0x0200;
export const STOP_FLAG: number = 0x0400;

export function getPackedFlags(destroy: boolean,
                               nullThing: boolean,
                               start: boolean,
                               stop: boolean): number {
    const bitFlags: number = ((destroy) ? DESTROY_FLAG: NO_FLAG) |
                            ((nullThing) ? NULL_FLAG: NO_FLAG) |
                            ((start) ? START_FLAG: NO_FLAG) |
                            ((stop) ? STOP_FLAG: NO_FLAG);
    return bitFlags;
}

Doing the above produces this kind of output:

tslint --project ./tsconfig.json --format verbose --force

ERROR: (no-bitwise) C:/git/my-stuff/src/index.ts[393, 34]: Forbidden bitwise operation
ERROR: (no-bitwise) C:/git/my-stuff/src/index.ts[393, 34]: Forbidden bitwise operation
ERROR: (no-bitwise) C:/git/my-stuff/src/index.ts[393, 34]: Forbidden bitwise operation

The authors of TSLint have a strategy of setting this as default error. However, the Typescript compiler and proper programming usage dictates this is correct use of the | operator. In cases, where you intend to use bitwise, calling it an error is just plain silly.

I don't know how to turn off this linting issue on a case-by-case basis, but keep the global setting unchanged.


Solution

  • Fortunately, you can disable this on a single line basis, as follows:

    export function getPackedFlags(destroy: boolean,
                                   nullThing: boolean,
                                   start: boolean,
                                   stop: boolean): number {
        // tslint:disable-next-line:no-bitwise
        const bitFlags: number = ((destroy) ? DESTROY_FLAG: NO_FLAG) |
                                ((nullThing) ? NULL_FLAG: NO_FLAG) |
                                ((start) ? START_FLAG: NO_FLAG) |
                                ((stop) ? STOP_FLAG: NO_FLAG);
        return bitFlags;
    }