0

I want to quickly disable all console.[log, time, error] messages in my code. I am aware of what has been asked before for javascript. But Typescript is complaining of my "solution" bellow:

    const konsole = {
        log:()=>{},
        time:()=>{},
        timeEnd:()=>{},
        error:()=>{}
    }
    (!dev) && console = konsole

Where dev is a boolean that is true when I am in development mode.

Typescript complaints: This expression is not callable. I don't understand the complaint and what should I do instead.

kelsny
  • 23,009
  • 3
  • 19
  • 48
Fred Guth
  • 1,537
  • 1
  • 15
  • 27

2 Answers2

1

You can create a function that would iterate the console properties and overwrite the methods:

const noop = (...args: any[]): any => {};

const disable = (con: Console) => {
  (Object.keys(con) as (keyof Console)[])
    .forEach((key) => {
      if(typeof con[key] === "function" ) {
        con[key] = noop;
      }
    });
};

working example

Teneff
  • 30,564
  • 13
  • 72
  • 103
1

Your code as it stands:

    const konsole = {
        log:()=>{},
        time:()=>{},
        timeEnd:()=>{},
        error:()=>{}
    }
    (!dev) && console = konsole

Is interpreted as this:

    const konsole = ({
        log:()=>{},
        time:()=>{},
        timeEnd:()=>{},
        error:()=>{}
    }(!dev) && console = konsole);

You are trying to call an object as a function, which is why TypeScript is warning you against this runtime error.

You can either use semicolons or remove the parentheses around !dev:

    const konsole = {
        log:()=>{},
        time:()=>{},
        timeEnd:()=>{},
        error:()=>{}
    }; // here
    !dev && console = konsole // or no parens here
kelsny
  • 23,009
  • 3
  • 19
  • 48