gpt4 book ai didi

javascript - TSLint 'property does not exist on type' VS firefox 调试器行为

转载 作者:行者123 更新时间:2023-12-03 00:49:27 24 4
gpt4 key购买 nike

首先:对于这个不准确的标题感到抱歉。我会澄清这个问题。

在我的公司,我们使用 TypeScript/React/JavaScript 开发 Web 应用程序。我使用 VS Code 作为 IDE,并启用了 tslint。我继续前同事的工作。

有一个HTMLElement存储在变量中,并对其调用 querySelector 函数。目的是获取 id 为“someID”的元素/标签,并获取该元素的“offsetTop”值:

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

在 VS Code 中,tslint 引发错误“类型‘Element’上不存在属性‘offsetTop’。”这是因为 querySelector 返回 Element 类型的元素,但属性“offsetTop”是为 HTMLElement 定义的。

现在,当我使用 Chrome 调试器时,在“const tmp = ...”行处中断,并通过将鼠标指针移到变量上来显示“tmp”的属性,它会显示属性“offsetTop”。

为什么?

提前致谢

编辑

我现在的解决方案是:

const offset_top = tmp.firstChild.parentElement.offsetTop;

它正在工作,但我仍然对为什么 Firefox 调试器显示该属性非常感兴趣。

最佳答案

首先回答你的问题:为什么 tslint 提出“属性‘offsetTop’在类型‘Element’上不存在。这是因为 Typescript 定义了一些类型,默认类型和自定义类型。对于 Typescript Element 是自定义类型,默认类型是数字、字符串、 bool 值因此,当您使用返回类型为 Element 的结果的 querySelector 时,这会将 const tmp 的类型更改为 Element,因为您尚未为其声明任何类型。
引用:https://www.typescriptlang.org/docs/handbook/basic-types.html
解决方案:通过执行以下操作自行设置常量的类型:

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

关于javascript - TSLint 'property does not exist on type' VS firefox 调试器行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53115977/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com