类型'HTMLElement'上不存在Typescript属性'style'

Dae*_*lus 8 typescript

虽然我的代码工作(下面),但是typescript会抛出错误,说"属性'样式'在类型'HTMLElement'上不存在."

正如您所看到的,我通过jQuery和元素的ID抓取元素.

$(this.id).click(function () {
  this.style.display = 'none';
});
Run Code Online (Sandbox Code Playgroud)

但这会导致以下错误:

`TS2339: Property 'style' does not exist on type 'HTMLElement'`.
Run Code Online (Sandbox Code Playgroud)

我不确定处理这个ts错误的正确方法是什么.

有人会让我知道吗?

先感谢您.

更多代码,因为它被请求:

`/**
* Class represents a flash message
*/
export class FlashMessage {    
flashMessageParentDivID:string;
iconID:string;
textID:string;
$: JQuery;

/**
 * 
 * @param {string} flashMessageParentDiv - the string of the div's ID.
 */ 
constructor (flashMessageParentDiv: string, $: JQuery) {
    this.flashMessageParentDivID = "#"+flashMessageParentDiv;
    this.iconID = "#flash-message-icon",
    this.textID = "#flash-message-text";
    this.$ = $;
}

/**
 * Displays the passed in message with the appropriate status.
 * @param {string} message - the message we want to flash.
 * @param {string} status: either 'error' or 'success'
 */
showWithMessage = function (message: string, status: string) {
    //@todo: maybe throw an error if status does not equal error or   success.
    this.clearAndCreateFlashMessageInnerds();
    this.$(this.flashMessageParentDivID).removeAttr("class");
    this.$(this.flashMessageParentDivID).addClass(status);

    this.$(this.iconID).removeAttr("class");
    this.$(this.iconID).addClass("k-icon k-i-" + status);

    this.$(this.textID).text(message);
    this.$(this.flashMessageParentDivID).show();   

    this.$(this.flashMessageParentDivID).click(function () {
        (<any>this).style.display = 'none';
    });
};
Run Code Online (Sandbox Code Playgroud)

...`

打字错误

Man*_*vit 28

在你的方法中使用它

(<HTMLElement>document.querySelector('#yourDomElmentID')).style.display = 'none';
Run Code Online (Sandbox Code Playgroud)

测试代码

我在我的代码中测试你的代码编译成功.

  • 虽然此代码段可能是解决方案,但包括解释确实有助于提高帖子的质量.请记住,您将来会回答读者的问题,而这些人可能不知道您的代码建议的原因 (4认同)