Reputation: 2956
I've got code similar to:
document.querySelectorAll('.thing').forEach(el => el.style.color = 'red');
The type hint system in VsCode marks el.style
as missing from Element
. I can fix this with:
/** @type {NodeListOf<HTMLElement>} */
const things = document.querySelectorAll('.thing');
things.forEach(el => el.style.color = 'red');
It seems wrong to create a var for the sole purpose of keeping VsCode's type system happy.
If I were using typescript, I think I could do
document.querySelectorAll<HTMLElement>('.thing') // etc...
Is there a way to tell VsCode's type system which type I expect out of a generic method?
Upvotes: 3
Views: 1435
Reputation: 65513
You can use a jsdoc cast for this:
// @ts-check
(/** @type {NodeListOf<HTMLElement>} */ (document.querySelectorAll('.thing'))).forEach(el => el.style.color = 'red');
Note that you must wrap the target of the cast ((document.querySelectorAll('.thing')
) in parens so that the type applies to the correct expression.
Upvotes: 3