英文:
Property 'focus' does not exist on 'Element'?
问题
Creating a keyboard navigation, and facing the following issue:
let currentActive = document.activeElement;
if (e.key === "ArrowLeft") {
currentActive.previousElementSibling.focus();
}
The code works as expected, but TypeScript complains that "Property 'focus' does not exist on 'Element'?" - the currentActive
is an <img />
tag.
I've tried assigning the currentActive to be an HTMLElement, by doing so:
let currentActive = document.activeElement as HTMLCollectionOf<HTMLElement>
, but it doesn't seem to like that.
What am I missing?
英文:
Creating a keyboard navigation, and facing the following issue:
let currentActive = document.activeElement;
if (e.key === "ArrowLeft") {
currentActive.previousElementSibling.focus();
}
The code works as expected, but TypeScript complains that Property 'focus' does not exist on 'Element'?
- the currentActive
is an <img />
tag.
I've tried assigning the currentActive to be a HTMLElement, by doing so:
let currentActive = document.activeElement as HTMLCollectionOf<HTMLElement>
, but it doesn't seem to like that.
What am I missing?
答案1
得分: 41
我建议尝试类似以下的代码:
let currentActive = document.activeElement;
if (e.key === "ArrowLeft") {
(currentActive.previousElementSibling as HTMLElement)?.focus();
}
请注意,可选链操作符自 TypeScript 3.7 起可用。
英文:
I would suggest trying something like this:
let currentActive = document.activeElement;
if (e.key === "ArrowLeft") {
(currentActive.previousElementSibling as HTMLElement)?.focus();
}
Note that optional chaining is available since TypeScript 3.7
答案2
得分: 19
我遇到了相同的问题,并通过定义我从 queryselector
预期的元素类型来解决它。在我的情况下,我预期的是一个 input
元素,所以我这样做了:
document.querySelector<HTMLInputElement>(`input[name=${element-name}]`)?.focus()
英文:
I had the same problem and I solved it by defining the type of the element I was expecting from queryselector
. In my case I was expecting an input
element, so I did:
document.querySelector<HTMLInputElement>(`input[name=${element-name}]`)?.focus()
答案3
得分: 13
你需要说服 TS(TypeScript)currentActive.previousElementSibling
的类型是 HTMLElement
。
作为额外的提示,我建议你也要说服自己,以避免控制台出现一些红色交叉符号。也许可以使用类似于 currentActive?.previousElementSibling?.focus?.();
的方式。
英文:
You need to convince TS that currentActive.previousElementSibling
is of type HTMLElement
.
As a bonus tip I would recommend to convince yourself as well avoiding some red crosses in your console. Maybe something along the lines of currentActive?.previousElementSibling?.focus?.();
答案4
得分: 12
使用 as
告诉 TypeScript 这是一个 HTMLElement:
(currentActive.previousElementSibling as HTMLElement).focus();
英文:
Use as
to tell TS its a HTMLElement:
(currentActive.previousElementSibling as HTMLElement).focus();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论