Javascript 扩展HtmleElement原型

Javascript 扩展HtmleElement原型,javascript,angular,typescript,Javascript,Angular,Typescript,我试图在main.ts中扩展HtmleElement对象的原型,以便在整个Angular 6项目中使用它 但是我得到的属性'fadeOut'在类型'HTMLElement'上不存在 HTMLElement.prototype.fadeOut = function(duration: number = 300): Promise<void> { const keyframes: AnimationKeyFrame[] = [{ opacity: 1 }, { opacity: 0

我试图在
main.ts
中扩展HtmleElement对象的原型,以便在整个Angular 6项目中使用它

但是我得到的
属性'fadeOut'在类型'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();
  });
};
#圆圈{
高度:100px;
宽度:100px;
利润率:50像素;
边界半径:50%;
背景色:#0f477f;
}

您需要添加一个定义,以便与原始接口相匹配,在原始接口中,您定义了要添加到
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();
    });
};
接口HTMLElement{
淡出(持续时间:个数):承诺
}
//现在可以工作了
HTMLElement.prototype.fadeOut=函数(持续时间:number=300):承诺{
常量关键帧:AnimationKeyFrame[]=[{opacity:1},{opacity:0}];
返回新承诺(解决=>{
const animation:animation=this.animate(关键帧、持续时间);
animation.onfinish=()=>resolve();
});
};
如果代码位于模块中,则需要在全局命名空间中声明接口

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;
声明全局{
接口HTMLElement{
淡出(持续时间:个数):承诺
}
}
HTMLElement.prototype.fadeOut=函数(持续时间:number=300):承诺{
常量关键帧:AnimationKeyFrame[]=[{opacity:1},{opacity:0}];
返回新承诺(解决=>{
const animation:animation=this.animate(关键帧、持续时间);
animation.onfinish=()=>resolve();
});
};
出口var x;

也许HtmleElement.prototype['fadeOut']有效。如果有效,那么OP尝试使用的方法也会有效。尝试使用该方法的代码到底是什么样子的?一旦找到原型,我想你的函数可以是:
函数(duration:number=300){返回这个。动画([{opacity:1},{opacity:0}],duration)。finished;}
我刚刚添加了一个代码段,因此代码可以正常工作@SeanBright你说得对!必须深入研究这个惊人的API。谢谢代码从一开始就可以工作,但它更像是一个lint问题。不幸的是,添加接口似乎无法解决此问题。@Kodebryan这不是lint问题,而是Typescript编译问题,编译器仍将发出语义问题代码。添加了一个可以与模块一起工作的版本,现在应该可以在你的angular应用程序中工作了。现在可以完美工作了,你太棒了!