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:

JavaScript

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

JavaScript

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:

JavaScript

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:

JavaScript

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