Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 490
Keith Avatar asked Jan 24 '26 16:01

Keith


1 Answers

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.

like image 110
Keith Avatar answered Jan 27 '26 05:01

Keith



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!