Skip to content
Advertisement

Type assert an element in a JS file with @ts-check

I have a JS file with a // @ts-check directive, using JSDoc comments to denote types.

The problem is that the elements fail type checks when retrieved from the document.

So we have in HTML:

<input id="myInput">...

When I get this element in JS the type checking throws an error:

// @ts-check
const myInput = document.getElementById('myInput');
myInput.value = 'foobar';

Property ‘value’ does not exist on type ‘HTMLElement’

If I specify the expected type with a JSDoc @type comment then that also fires an error:

// @ts-check

/** @type {HTMLInputElement} */
const myInput = document.getElementById('myInput');
myInput.value = 'foobar';

Type ‘HTMLElement’ is not assignable to type ‘HTMLInputElement’.
Property ‘accept’ is missing in type ‘HTMLElement’.

If I was in TS, I could use document.getElementById('myInput') as HTMLInputElement to tell it that I expect this type.

How do I do this in JS with @ts-check?

Advertisement

Answer

The fix for this is to put the @type declaration between the variable and the retrieval, and adding ().

Like this:

// @ts-check

const myInput = /** @type {HTMLInputElement} */ (document.getElementById('myInput'));
myInput.value = 'foobar';

This syntax is fairly clunky and horrible, but they’ve closed the bug so I guess the above syntax is the official way to handle this.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement