How to enforce a type when type checking is enabled in Javascript with checkJS?

35 Views Asked by At

In VS Code, you can enable type checking for javascript with this jsconfig.json file:

{
    "compilerOptions": {
        "checkJs": true
    }
}

This works, but will give type errors when VS Code can't determine the type. For example:

const chatfield = document.querySelector("#chatinput")
console.log(chatfield.value)

ERROR:

Property 'value' does not exist on type 'Element'.

In Typescript you would do:

const chatfield = document.querySelector("#chatinput") as HTMLInputElement

What is the javascript equivalent for this?

1

There are 1 best solutions below

2
Phil On BEST ANSWER

See the @type JSDoc reference

/**
 * @type {HTMLInputElement}
 */
const chatfield = document.querySelector("#chatinput");

or as an inline cast

const chatfield = /** @type {HTMLInputElement} */(document.querySelector("#chatinput"));