I had the following javascript in my error logging code, which defines console.log
for certain browsers where it doesn't exist (IE doesn't/didn't have it defined unless the debug tools are open).
if (typeof console == "undefined")
{
window.console = { log: function (msg) { } };
}
The problem when trying to upgrade the js to Typescript is that window.console
is defined as being of the Console
interface type and since I'm not specifying everything it (obviously) doesn't compile.
interface Console {
info(message?: any, ...optionalParams: any[]): void;
profile(reportName?: string): void;
assert(test?: boolean, message?: string, ...optionalParams: any[]): void;
msIsIndependentlyComposed(element: Element): boolean;
clear(): void;
dir(value?: any, ...optionalParams: any[]): void;
warn(message?: any, ...optionalParams: any[]): void;
error(message?: any, ...optionalParams: any[]): void;
log(message?: any, ...optionalParams: any[]): void;
profileEnd(): void;
}
How can tell it to ignore this interface and just let me redefine window.console
.
My best effort guess doesn't work
window.console = { log: function (msg) { } } : any;
A shorter solution is to just use a type assertion:
window.console = <any>{ log: function (msg) { } };
And even use a lambda:
window.console = <any>{ log: () => { } };
The interface is going to force you to create all functions. If you try to override the interface, it will give you a Duplicate Identifier
error. So, here's the full stub to save you time :)
window.console =
{
info: (message?: any, ...optionalParams: any[]) =>
{
// ...
},
profile: (reportName?: string) =>
{
// ...
},
assert: (test?: boolean, message?: string, ...optionalParams: any[]) =>
{
// ...
},
msIsIndependentlyComposed: (element: Element) =>
{
return false;
},
clear: () =>
{
// ...
},
dir: (value?: any, ...optionalParams: any[]) =>
{
// ...
},
warn: (message?: any, ...optionalParams: any[]) =>
{
// ...
},
error: (message?: any, ...optionalParams: any[]) =>
{
// ...
},
log: (message?: any, ...optionalParams: any[]) =>
{
// ...
},
profileEnd: () =>
{
// ...
},
count: (countTitle?: string) =>
{
// ...
},
groupEnd: () =>
{
// ...
},
time: (timerName?: string) =>
{
// ...
},
timeEnd: (timerName?: string) =>
{
// ...
},
trace: () =>
{
// ...
},
group: (groupTitle?: string) =>
{
// ...
},
dirxml: (value: any) =>
{
// ...
},
debug: (message?: string, ...optionalParams: any[]) =>
{
// ...
},
groupCollapsed: (groupTitle?: string) =>
{
// ...
},
select: (element: Element) =>
{
// ...
},
};
Alternate Solution
If you don't want to write out all methods, you can fool TypeScript like this.
var x: any =
{
log: (msg) =>
{
//...
}
};
window.console = <Console>x;
I suppose I could do this :-/
var w:any = window;
w.console = { log: function (msg) { } };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With