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.
CodePudding user response:
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;
}
});
};
CodePudding user response:
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