我需要让打字稿停止抱怨我的代码。它在浏览器中运行良好,但全屏 api 还不是官方的,所以打字稿定义不是最新的。
我正在调用 document.documentElement.msRequestFullscreen。这会导致类型错误:
Property 'msRequestFullscreen' does not exist on type 'HTMLElement'.
在查看 lib.d.ts 时,我发现:
documentElement: HTMLElement;
所以 documentElement 被设置为 HTMLElement 类型。我尝试添加自定义定义来覆盖 documentElement。我的自定义定义:
// Extend Document Typings
interface Document {
msExitFullscreen: any;
mozCancelFullScreen: any;
documentElement: {
msRequestFullscreen: any;
mozRequestFullScreen: any;
}
}
我尝试扩展 Document 的接口,但它给出了错误
错误是:
lib.d.ts:5704:5
Duplicate identifier 'documentElement'.
我的打字稿课
export class ToggleFullScreen {
viewFullScreenTriggerID: string;
viewFullScreenClass: string;
cancelFullScreenClass: string;
viewFullscreenElem: any;
activeIcon: string;
notFullscreenIcon: string;
isFullscreenIcon: string
constructor() {
this.viewFullScreenTriggerID = "#fullScreenTrigger";
this.viewFullScreenClass = "not-fullscreen";
this.cancelFullScreenClass = "is-fullscreen";
this.notFullscreenIcon = "/assets/icon/fullscreen-enter.svg";
this.isFullscreenIcon = "/assets/icon/fullscreen-exit.svg";
this.activeIcon = this.notFullscreenIcon;
}
toggleFullScreen() {
this.viewFullscreenElem = document.querySelector(this.viewFullScreenTriggerID);
if (this.viewFullscreenElem.classList.contains(this.viewFullScreenClass)) {
var docElm = document.documentElement;
if (docElm.requestFullscreen) {
docElm.requestFullscreen();
} else if (docElm.msRequestFullscreen) {
docElm.msRequestFullscreen();
} else if (docElm.mozRequestFullScreen) {
docElm.mozRequestFullScreen();
} else if (docElm.webkitRequestFullScreen) {
docElm.webkitRequestFullScreen();
}
this.viewFullscreenElem.classList.toggle(this.viewFullScreenClass);
this.viewFullscreenElem.classList.toggle(this.cancelFullScreenClass);
this.activeIcon = this.isFullscreenIcon;
}
else if (this.viewFullscreenElem.classList.contains(this.cancelFullScreenClass)) {
if (document.exitFullscreen) {
document.exitFullscreen();
} else if (document.msExitFullscreen) {
document.msExitFullscreen();
} else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
} else if (document.webkitCancelFullScreen) {
document.webkitCancelFullScreen();
}
this.viewFullscreenElem.classList.toggle(this.viewFullScreenClass);
this.viewFullscreenElem.classList.toggle(this.cancelFullScreenClass);
this.activeIcon = this.notFullscreenIcon;
}
}
}
什么是让打字稿编译错误停止的正确方法?
更新:我找到了一种解决方法。我没有尝试覆盖设置为 HTMLElement 类型的 documentElement,而是扩展了 HTMLElement 并添加了缺少的属性。
// Extend Document Typings
interface Document {
msExitFullscreen: any;
mozCancelFullScreen: any;
}
interface HTMLElement {
msRequestFullscreen(): void;
mozRequestFullScreen(): void;
}