2

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?

opensas
  • 60,462
  • 79
  • 252
  • 386

3 Answers3

1

You can type the elements with one of the interfaces found here: https://developer.mozilla.org/en-US/docs/Web/API#interfaces

Stephane Vanraes
  • 14,343
  • 2
  • 23
  • 41
1

As Stephane mentioned, you can find a list of web interfaces at https://developer.mozilla.org/en-US/docs/Web/API#interfaces. The actual type information comes from lib.dom.d.ts which is generated from the webidl files produced by Microsoft Edge.

For the various element types, you'll want to look at the interfaces that start with "HTML". In this specific case, you care about HTMLElement and HTMLButtonElement.

Scott González
  • 1,917
  • 16
  • 10
1

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();
  }
opensas
  • 60,462
  • 79
  • 252
  • 386