简体   繁体   English

分配变量类型时出错

[英]Error assigning variable type

I'm afraid I'm not sure if this is a question about WebStorm , Angular2 or Typescript . 恐怕我不确定这是否是有关WebStormAngular2Typescript的问题

I have an Angular2 build set up and am using WebStorm 2016.1.2 to edit with. 我已经设置了Angular2构建,并且正在使用WebStorm 2016.1.2进行编辑。 One of my components gets a reference to a DOM element using a simple document.getElementById('some-el'); 我的组件之一使用简单的document.getElementById('some-el');来获取对DOM元素的引用document.getElementById('some-el'); and passes this to a service method: 并将其传递给服务方法:

calc(el:HTMLElement){
    this.height = el.offsetHeight;
    this.width = el.offsetWidth;

    let span:HTMLElement = el.querySelector("span");
    this.pos = span.offsetTop - span.offsetHeight;
}

Everything works fine and I don't get any errors in the browser but I do get an error in WebStorm linked to el.querySelector("span"); 一切正常,在浏览器中没有任何错误,但在链接到el.querySelector("span");中却出现错误el.querySelector("span");

The error says: Initializer type Element is not assignable to variable type HTMLElement 错误消息: Initializer type Element is not assignable to variable type HTMLElement

I don't know if this a problem with WebStorm or if I am actually typing things wrong. 我不知道这是WebStorm的问题还是我键入的错误。 If I set the type of span to Element the error disappears but then the offsetTop and offsetHeight are highlighted as incorrect?? 如果将span类型设置为Element则错误消失,但是offsetTopoffsetHeight会突出显示为不正确?

As the actual build doesn't seem to suffer when I run it I just wonder if this is something in my code I need to fix or something in my editor that I can ignore? 由于运行时实际构建似乎没有受到影响,我只是想知道这是我需要修复的代码中的内容还是编辑器中可以忽略的内容?

Cheers for your help 助您一臂之力

You just need to cast it: 您只需要强制转换:

calc(el:HTMLElement){
    this.height = el.offsetHeight;
    this.width = el.offsetWidth;

    let span:HTMLElement = <HTMLElement> el.querySelector("span");
    this.pos = span.offsetTop - span.offsetHeight;
}

Or you can use type assertion : 或者您可以使用类型断言

let span:HTMLElement = el.querySelector("span") as HTMLElement;

What happens is that querySelector returns Element and not HTMLElement as you declared the type of span to be. 发生的情况是,在您声明span类型querySelectorquerySelector返回Element而不是HTMLElement But you can tell the compiler to "trust you" that you know that it's indeed an HTMLElement . 但是您可以告诉编译器“信任您”,您知道它确实是HTMLElement

You can also use HTMLSpanElement instead of the HTMLElement which is more specific, just like HTMLElement is more specific than Element (that's why when you changed it to Element the offsetTop and offsetHeight weren't available). 您也可以使用HTMLSpanElement而不是更具体的HTMLElement ,就像HTMLElementElement更特定(这就是为什么将其更改为Element offsetTopoffsetHeight不可用的原因)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM