使用typescript重新定义window.console

时间:2014-05-23 02:15:27

标签: typescript

我的错误记录代码中有以下javascript,它为certain browsers where it doesn't exist定义console.log(除非调试工具处于打开状态,否则IE没有/没有定义)。

if (typeof console == "undefined")
{
    window.console = { log: function (msg) { } };
}

尝试将js升级到Typescript时的问题是window.console被定义为Console接口类型,因为我没有指定它(显然)不能编译。

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;
}

如何告诉它忽略此界面,让我重新定义window.console

我的最大努力猜测不起作用

window.console = { log: function (msg) { } } : any;

3 个答案:

答案 0 :(得分:4)

更简短的解决方案是使用类型断言

window.console = <any>{ log: function (msg) { } };

甚至使用lambda:

window.console = <any>{ log: () => { } };

答案 1 :(得分:3)

界面将强制您创建所有功能。如果您尝试覆盖界面,则会出现Duplicate Identifier错误。所以,这里有完整的存根来节省你的时间:)

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) => 
    {
        // ...
    },
};

替代解决方案

如果您不想写出所有方法,可以像这样欺骗TypeScript。

var x: any = 
{
    log: (msg) =>
    {
        //...
    }
};
window.console = <Console>x;

答案 2 :(得分:1)

我想我可以这样做: - /

 var w:any = window;
 w.console = { log: function (msg) { } };