简体   繁体   English

TSLint“类型上不存在属性” VS FireFox调试器行为

[英]TSLint 'property does not exist on type' VS firefox debugger behavior

First: sorry for that unprecise title. 第一:对那个不精确的标题感到抱歉。 I will clearify the question. 我会澄清这个问题。

In my company we develope web applications using TypeScript/React/JavaScript. 在我公司,我们使用TypeScript / React / JavaScript开发Web应用程序。 I use VS Code as IDE with tslint enabled. 我使用VS Code作为启用了tslint的IDE。 I continue the work of a former co-worker. 我继续前同事的工作。

There is a HTMLElement stored in a variable and the querySelector-function is called on it. 有一个HTMLElement存储在变量中,并在其上调用querySelector-function。 The intent is to get the element/tag with the id "someID" and get the value of 'offsetTop' of this element: 目的是获取ID为“ someID”的元素/标签,并获取该元素的“ offsetTop”值:

// elem is the HTMLElement
const tmp = elem.querySelector('[id=" + someID + "');
const offset_top = tmp.offsetTop;

In VS Code tslint raises the error "Property 'offsetTop' does not exist on type 'Element'." 在VS Code中,tslint引发错误“类型'Element'上不存在属性'offsetTop'。” This is because querySelector returns an element of type Element, but the property 'offsetTop' is defined for HTMLElement. 这是因为querySelector返回类型为Element的元素,但是为HTMLElement定义了属性“ offsetTop”。

Now, when i use the Chrome debugger, break at the line 'const tmp = ... ' and show the properties of 'tmp' by moving the mouse pointer over the variable, it shows the property 'offsetTop'. 现在,当我使用Chrome调试器时,在行'const tmp = ...'处中断,并通过将鼠标指针移到变量上来显示'tmp'的属性,它显示了属性'offsetTop'。

Why? 为什么?

Thanks in advance 提前致谢

Edit 编辑

My solution now is: 我现在的解决方案是:

const offset_top = tmp.firstChild.parentElement.offsetTop;

which is working, but i'm still very interested in why firefox debugger shows the property. 这是可行的,但我仍然对为什么Firefox调试器显示该属性非常感兴趣。

First Answering your question: Why tslint raises that "Property 'offsetTop' does not exist on type 'Element'. It is because Typescript has some set of types defined, default types and custom types. For typescript Element is custom type and default types are number, string,boolean and any. So when you use querySelector which returns a result whose type is Element this in turn change the type of const tmp to Element as you have not declared any type for it. 首先回答您的问题:为什么tslint会提出类型“元素”上不存在“属性'offsetTop'。这是因为类型脚本定义了一些类型,默认类型和自定义类型。对于类型脚本,元素是自定义类型,默认类型是因此,当您使用querySelector返回一个类型为Element的结果时,这又将const tmp的类型更改为Element,因为您尚未为其声明任何类型。
reference: https://www.typescriptlang.org/docs/handbook/basic-types.html 参考: https : //www.typescriptlang.org/docs/handbook/basic-types.html
Solution: set type of your constant by yourself by doing this : 解决方案:您可以通过以下方式自行设置常量的类型:

const tmp: any = elem.querySelector('[id=" + someID + "');
const offset_top = tmp.offsetTop;

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

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