扩展 HTMLElement 原型

Kod*_*ant 4 javascript typescript angular

我正在尝试在 中扩展 HTMLElement 对象的原型main.ts,以便我可以在整个 Angular 6 项目中使用它。

但我得到了Property 'fadeOut' does not exist on type 'HTMLElement'.

HTMLElement.prototype.fadeOut = function(duration: number = 300): Promise<void> {
  const keyframes: AnimationKeyFrame[] = [{ opacity: 1 }, { opacity: 0 }];
  return new Promise(resolve => {
    const animation: Animation = this.animate(keyframes, duration);
    animation.onfinish = () => resolve();
  });
};
Run Code Online (Sandbox Code Playgroud)

HTMLElement.prototype.fadeOut = function(duration: number = 300): Promise<void> {
  const keyframes: AnimationKeyFrame[] = [{ opacity: 1 }, { opacity: 0 }];
  return new Promise(resolve => {
    const animation: Animation = this.animate(keyframes, duration);
    animation.onfinish = () => resolve();
  });
};
Run Code Online (Sandbox Code Playgroud)
const circle = document.getElementById('circle');

HTMLElement.prototype.fadeOut = function(duration = 300) {
  const keyframes = [{ opacity: 1 }, { opacity: 0 }];
  return this.animate(keyframes, duration).finished
};

circle.fadeOut(2000);
Run Code Online (Sandbox Code Playgroud)
#circle {
  height: 100px;
  width: 100px;
  margin: 50px;
  border-radius: 50%;
  background-color: #0f477f;
 }
 
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

我需要把这个代码放在哪里,以便我可以在任何地方使用这个方法?

您是否也看到了使此代码更清晰的可能性?

Tit*_*mir 7

您需要添加一个定义以与您定义要添加的额外功能的原始接口合并HTMLElement

interface HTMLElement {
    fadeOut(duration: number): Promise<void>
}

// Will now work 
HTMLElement.prototype.fadeOut = function (duration: number = 300): Promise<void> {
    const keyframes: AnimationKeyFrame[] = [{ opacity: 1 }, { opacity: 0 }];
    return new Promise(resolve => {
        const animation: Animation = this.animate(keyframes, duration);
        animation.onfinish = () => resolve();
    });
};
Run Code Online (Sandbox Code Playgroud)

如果代码在模块中,则需要在全局命名空间中声明接口

declare global {
    interface HTMLElement {
        fadeOut(duration: number): Promise<void>
    }

}
HTMLElement.prototype.fadeOut = function (duration: number = 300): Promise<void> {
    const keyframes: AnimationKeyFrame[] = [{ opacity: 1 }, { opacity: 0 }];
    return new Promise(resolve => {
        const animation: Animation = this.animate(keyframes, duration);
        animation.onfinish = () => resolve();
    });
};


export var x;
Run Code Online (Sandbox Code Playgroud)