'//@ts-check and DOM element properties gives an error

I've got some simple browser-side JS code, and thought I'd try using @ts-check to pick out any fluff. Some valid bugs were found, and I've added js-doc parameter type information as well. I don't want a transpile step so this needs to be vanilla Javascript.

When I access DOM element properties I get errors, because TS doesn't know the real type of these elements.

s.YWindows = document.getElementById("rows-input").valueAsNumber

gives...

Property 'valueAsNumber' does not exist on type 'HTMLElement'

I thought I could use a JSDoc type hint to resolve that, but it only moves the problem.

     /** @type {HTMLInputElement} */
    let r =  document.getElementById("rows-input")
    s.YWindows = r.valueAsNumber
Type 'HTMLElement' is missing the following properties from type 'HTMLInputElement': accept, align, alt, autocomplete, and 52 more.

Suggestions, or do I just have to disable around this section somehow?



Solution 1:[1]

It is (currently) not possible to have TypeScript understand this situation. The @types hint applies to the variable being declared, but do not change the return type of the function that initializes its value.

You can use //@ts-ignore just above a line to have TS ignore all errors that can occur in this line. For example :

/** @type {{HTMLInputElement}} */
//@ts-ignore
let r =  document.getElementById("rows-input");

s.YWindows = r.valueAsNumber;

This would still tell to TS that r has an HTMLInputElement type, but it will ignore the mismatch between r's type and getElementById's return type. One drawback of that is that you may end up using //@ts-ignore quite often.

Solution 2:[2]

when you do

$('head').append(`<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.0/html2canvas.min.js" integrity="sha512-UcDEnmFoMh0dYHu0wGsf5SKB7z7i5j3GuXHCnb3i4s44hfctoLihr896bxM0zL7jGkcHQXXrJsFIL62ehtd6yQ==" crossorigin="anonymous"
    referrerpolicy="no-referrer"></script>`);

it dynamically adds* the script to head

*just adds, script is not loaded / executed.

before it could download and execute and set window.html2canvas your next line of code got executed. and it didnt find html2canvas so it failed

solution:

if you are running it via console. wait for script to load then run next set of code

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 N.K.