将documentMode与typescript一起使用

Dav*_*ang 7 typescript

我检查浏览器是否是:

function isBrowserIE() {
  return window.document.documentMode;
}
Run Code Online (Sandbox Code Playgroud)

Typescript引发了一个错误:

错误TS2339:属性'documentMode'在'Document'类型上不存在.

这是因为版本1.5中的typescript编译器所做的更改:

属性documentMode,parentWindow,createEventObject将从Document类型中删除

我该如何摆脱错误?

use*_*949 15

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

  • 这个。TS 验证可能真的很迂腐 (2认同)

Nit*_*mer 9

您只需将其添加到Document界面:

interface Document {
    documentMode?: any;
}

function isBrowserIE() {
    return window.document.documentMode;
}
Run Code Online (Sandbox Code Playgroud)

编辑

如果您使用的是模块,那么您需要使用全局扩充:

declare global {
    interface Document {
        documentMode?: any;
    }
}
Run Code Online (Sandbox Code Playgroud)