Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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"));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading