Reputation: 1103
Let's say i have a HTML element as following:
<progress value="1" max="10" id="site_progress"></progress>
VSCode shows a problem ('Property "max" does not exist on type "Element"'), if i select this element like this:
const progress = document.querySelector('#site_progress');
progress.max = 9;
There will be no problems, if i select via element selector:
const progress = document.querySelector('progress');
progress.max = 9;
Can i do something like type assertion to avoid this kind of behavior or what are good practises to handle this problem in regular javascript?
Upvotes: 2
Views: 83
Reputation: 24191
Personally I would just move to TS, but even then you would still need to cast. To cast the type in JS you can do ->
/** @type HTMLProgressElement */
const progress = document.querySelector('#id');
progress.max = 9;
In Typescript it would have been like ->
const progress = document.querySelector('#id') as HTMLProgressElement;
progress.max = 9;
Another nice feature, you can create type guards, and this also helps the compiler.
eg, this below will work in both TS & JS.
const progress = document.querySelector('#id');
if (progress instanceof HTMLProgressElement)
progress.max = 9;
One slight issue with the above, is if #id is not a Progress it will silently continue. So another option is to throw an exception, this also acts as a type guard, but allows you to throw logical error messages when things are not right.
eg..
const progress = document.querySelector('#id');
if (!(progress instanceof HTMLProgressElement))
throw new Error('#id not a progress');
progress.max = 9;
Upvotes: 4