javascripttypecheckingcheckjs

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


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?


Solution

  • See the @type JSDoc reference

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

    or as an inline cast

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