将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。有什么亮点或建议吗?
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
...
}