'TypeScript expression is not callable when trying to disable console methods
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.
Solution 1:[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
Solution 2:[2]
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;
}
});
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | hittingonme |
| Solution 2 | Teneff |
