typescript 类型“HTMLElement”上不存在打字稿属性“样式”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47997480/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Typescript Property 'style' does not exist on type 'HTMLElement'
提问by Daedalus
Although my code works (below), typescript is throwing errors saying "Property 'style' does not exist on type 'HTMLElement'."
尽管我的代码有效(如下),但打字稿会抛出错误,提示“类型 'HTMLElement' 上不存在属性 'style'。”
As you can see I am grabbing the element via jQuery & the element's ID.
如您所见,我正在通过 jQuery 和元素的 ID 获取元素。
$(this.id).click(function () {
this.style.display = 'none';
});
But this causes the following error:
但这会导致以下错误:
`TS2339: Property 'style' does not exist on type 'HTMLElement'`.
I am not sure what would be the proper way of handling this ts error.
我不确定处理这个 ts 错误的正确方法是什么。
Would anyone let me know?
有人会告诉我吗?
Thank you in advance.
先感谢您。
more code, since it was requested:
更多代码,因为它被要求:
`/**
* 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';
});
};
...`
...`
回答by Manohar Gavit
回答by Daedalus
As Manohar Gavit suggested, I needed to typecast. But, his suggestion did not fix my problem. For some reason my jQuery definition file does not recognize HTMLElement
as having the style
property, but as you can see below... the definition file does accept any
with that property.
正如 Manohar Gavit 建议的那样,我需要进行类型转换。但是,他的建议并没有解决我的问题。出于某种原因,我的 jQuery 定义文件无法识别HTMLElement
为具有该style
属性,但正如您在下面看到的那样......定义文件确实接受any
了该属性。
`$(this.id).click(function () {
(<any>this).style.display = 'none';
});`