Adding types to HTMLElements working with Svelte and TypeScript

Viewed 625

I'm working with Svelte and typescript, and I'd like to add type definitions to the html elements I'm referencing.

For example I have something like this:

<script>
let closeButtonEl;
let prevFocused;

[...]
prevFocused = document.activeElement;
[...]
</script>
[...]
<button bind:this={closeButtonEl}>Click me</button>

That is, I have a closeButtonEl which I know for sure is a button, and a prevFocused which is an HTMLElement with a focus() method.

What type should I use for each of them? And where is that kind of things documented?

3 Answers

Just to complete the answer

Like previously said by Scot and Stephane, the types of those elements can be found at https://developer.mozilla.org/en-US/docs/Web/API#interfaces

And for this particular case, I found these two solutions:

  let closeButtonEl: HTMLButtonElement;
  let prevFocusedEl: Element & { focus?: () => void };

document.activeElement is of the Element type, in this case I also define that it has a focus method.

THe other solution is to cast document.activeElement as an HTMLElement which comes with the focus() method, like this:

  let closeButtonEl: HTMLButtonElement;
  let prevFocusedEl: HTMLElement;

  $: if (isOpen) {
    prevFocusedEl = <HTMLElement> document.activeElement;
    closeButtonEl && closeButtonEl.focus();
  }
Related