typescript

Is it Possible in TypeScript to Disable the Rule Behind TS(1345)


TypeScript will throw an error ("An expression of type 'void' cannot be tested for truthiness.ts(1345)") with valid debugging code like:

const getFooPlusTwo = (foo) => console.log(foo) || foo + 2;

There are various hacks to work around that (adding +, ,, etc.) but they don't work in all circumstances ... and more importantly, they're unnecessary work for no benefit (JS works perfectly fine without them).

Most TypeScript rules can be turned off. Is there any TypeScript (or ESLint) rule that I can disable to make TypeScript not throw these errors?


Solution

  • You can augment global console object to make its methods return undefined instead of void. It's safe since console.log really returns undefined unconditionally. Just this (you can add other console methods here as well):

    declare global { 
       interface Console { 
          log(msg: any, ...args: any[]): undefined; 
       } 
    }
    
    const getFooPlusTwo = (foo: string) => console.log(foo) || foo + 2;
    

    Playground Link (read this to understand declare global, you likely need that, but not in playground).

    This won't allow generally using void in such boolean chains, and that's probably good: if you accept a callback returning void, you can accidentally use it in callback() || 'something' and be disappointed when that callback returns 1.

    function test(callback: () => void) {
        return callback() || 'something'
    }
    test(() => 1)
    

    "An expression of type 'void' cannot be tested for truthiness" is the only error typescript raises for the snippet above, so disabling it may really accept a broken code.