3

JavaScript の場合、Internet Explorer が F12 を押さずに console.log を処理できるようにするための次の解決策を見つけました。 「コンソール」は Internet Explorer の未定義エラーです

ただし、Typescript で次の行を使用すると、コンパイルできません。

if (!console) console = {log: function() {}};

何か案は?

4

4 に答える 4

4

You are getting an error because the object literal you wrote doesn't have all the same members as a regular console. Simplest fix would just be to type-assert as any:

if (!console) console = <any>{log: function() {}};

Obviously you'll need to not call anything off console other than log.

于 2012-10-23T16:42:58.303 に答える
3

これを処理する最も簡単な方法は、コンソールを抽象化することです...

class Logger {
    static log(message: string) {
        if (typeof window.console !== 'undefined') {
            window.console.log(message);
        }
    }
}

Logger.log("Works with the console and doesn't ever error");

これにより、メッセージウィンドウでコンソールなしのシナリオを処理したり、サーバーにエラーを記録したり、コンソールに記録する以外にやりたいことをしたりするなど、他の可能性も開かれます-コードの実行も簡単になりますウィンドウのないコンテキストで!

于 2012-10-23T22:22:45.530 に答える
0

console.js を見てください。すべてのブラウザでのコンソール ロギングなどを処理します。typescript でコンパイルするには、console.d.ts モジュール定義で console.log を定義し、console.log を使用する場所で d.ts ファイルを参照する必要があります。

于 2012-10-24T09:52:48.240 に答える