(Angular)自定义Web元素的Typescript类型

问题描述 投票:0回答:2

将Angular组件与相应的元素主机一起传递给TypeScript中的方法,如下所示:

constructor(hostElementRef: ElementRef, ipeConfigurationService: IPEConfigurationService) {
  this.ipeConfigurationService = ipeConfigurationService;
  this.ipeConfigurationService.registerHostElement(hostElementRef.nativeElement);
}

public registerHostElement(value: HTMLElement) {
  this._hostElement = value;
}

public toggleFullScreen(): void {
    if (!this._isFullScreen && this._hostElement) {
        if (this._hostElement.requestFullscreen) {
            this._hostElement.requestFullscreen();
        } else if (this._hostElement.mozRequestFullScreen) {
            this._hostElement.mozRequestFullScreen();
        } else if (this._hostElement.webkitRequestFullscreen) {
            this._hostElement.webkitRequestFullscreen();
        } else if (this._hostElement.msRequestFullscreen) {
            this._hostElement.msRequestFullscreen();
        }
    } else if (this._isFullScreen && this._hostElement) {
        if (document.exitFullscreen) {
            document.exitFullscreen();
        } else if (document.webkitExitFullscreen) {
            document.webkitExitFullscreen();
        }
    }
}

运行时出错:“HTMLElement类型中不存在mozRequestFullScreen”。

如果我将hostElement更改为:any则没有问题。我想尽可能明确地声明类型用法,以防止尽可能多地使用any。有什么亮点或建议吗?

html angular typescript
2个回答
1
投票

HTMLElement界面只是没有这个属性。

如果内置类型不提供预期的属性,则可以合并或扩展接口,或者可以指定联合类型。

由于合并的接口将强加全局行为,因此不适合解决本地键入问题。

联盟类型:

public toggleFullScreen(): void {
  interface RequestFullscreen {
    mozRequestFullscreen(): void;
  }
  ...
  const hostElement = <HTMLElement & RequestFullscreen>this._hostElement;
  hostElement.mozRequestFullscreen
  ...
}

扩展接口:

public toggleFullScreen(): void {
  interface RequestFullscreenElement extends HTMLElement {
    mozRequestFullscreen(): void;
  }
  ...
  const hostElement = <RequestFullscreenElement>this._hostElement;
  hostElement.mozRequestFullscreen
  ...
}

合并本地接口(虽然它看起来有误导性,不能推荐):

public toggleFullScreen(): void {
  interface HTMLElement {
    mozRequestFullscreen(): void;
  }
  ...
  const hostElement = <HTMLElement>this._hostElement;
  hostElement.mozRequestFullscreen
  ...
}

0
投票

您收到该错误,因为HTMLElement没有mozRequestFullScreen属性或方法。检查here

您可能会在其他post中找到解决问题的一些方法

© www.soinside.com 2019 - 2024. All rights reserved.