matmik
matmik

Reputation: 670

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 a HTMLElement, by doing so: let currentActive = document.activeElement as HTMLCollectionOf<HTMLElement>, but it doesn't seem to like that.

What am I missing?

Upvotes: 39

Views: 44342

Answers (5)

Cristea
Cristea

Reputation: 1077

if (el instanceof HTMLElement) { el.focus()}

or in your case:

const htmlElement = currentActive.previousElementSibling

if (htmlElement instanceof HTMLElement) { htmlElement.focus()}

Upvotes: 2

Vishal SINGH
Vishal SINGH

Reputation: 149

Use as to tell TS its a HTMLElement:

(currentActive.previousElementSibling as HTMLElement).focus();

Upvotes: 14

geffting
geffting

Reputation: 221

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()

Upvotes: 22

Jonathan
Jonathan

Reputation: 9151

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?.();

Upvotes: 14

E. Boussardon
E. Boussardon

Reputation: 578

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

Upvotes: 49

Related Questions