在TypeScript 3中扩展Document对象

时间:2019-02-26 13:50:28

标签: typescript typescript-typings

当我在项目中使用TS 2时,以下工作正常。

我有一个扩展文档的接口:

//To avoid TypeScript errors when using experimental functions
export interface ExtendedDocument extends Document {
    msExitFullscreen?: any;
    mozCancelFullScreen?: any;
    msFullscreenElement?:any;
    mozFullScreenElement?: any;
  }

以及扩展HTMLBody的此接口:

//To avoid TypeScript errors when using experimental functions
export interface ExtendedHTMLBodyElement extends HTMLBodyElement {
    mozRequestFullScreen?: any;
    msRequestFullscreen?: any;
  }

这样我就可以使用浏览器特定的实验功能而不会出错:

        const htmlDocument: ExtendedDocument = document;
        const elem: ExtendedHTMLBodyElement = htmlDocument.getElementsByTagName('body')[0];
if (!htmlDocument.fullscreenElement && !htmlDocument.webkitFullscreenElement && !htmlDocument.msFullscreenElement && !htmlDocument.mozFullScreenElement) {
            if (elem.requestFullscreen) {
                elem.requestFullscreen();
            }
            else if (elem.mozRequestFullScreen) { /* Firefox */
                elem.mozRequestFullScreen();
            }
            else if (elem.msRequestFullscreen) { /* IE11 */
                elem.msRequestFullscreen();
            }
            else if (elem.webkitRequestFullscreen) { /* Chrome */
                elem.webkitRequestFullscreen();
            }
        }

我更新到TS 3.2,现在在构建项目时会引发以下错误: enter image description here

TS发生了什么变化,我必须对其代码进行哪些更改才能进行编译?

1 个答案:

答案 0 :(得分:0)

在当前的TS版本fullscreenElement中,Document类型不存在。因此,如果您确定fullscreenElement不会引发错误,则可以将其添加到ExtendedDocument接口定义中。

例如

export interface ExtendedHTMLBodyElement extends HTMLBodyElement {
   ...,
   fullscreenElement: ...
}