将documentMode与typescript一起使用

using documentMode with typescript

我通过以下方式检查浏览器是否为:

1
2
3
function isBrowserIE() {
  return window.document.documentMode;
}

Typescript引发错误:

Error TS2339: Property 'documentMode' does not exist on type 'Document'.

这是由于在1.5版的typescript编译器中所做的更改:

Properties documentMode, parentWindow, createEventObject are removed from type Document

如何摆脱错误?


我使用括号表示法来消除错误:
document['documentMode']


您可以简单地将其添加到Document界面:

1
2
3
4
5
6
7
interface Document {
    documentMode?: any;
}

function isBrowserIE() {
    return window.document.documentMode;
}

编辑

如果使用模块,则需要使用全局增强:

1
2
3
4
5
declare global {
    interface Document {
        documentMode?: any;
    }
}