使用jsdoc注释,调用时如何指定泛型函数的输出类型

Using jsdoc annotation, how do I specify the type to output of generic function when calling

我的代码类似于:

document.querySelectorAll('.thing').forEach(el => el.style.color = 'red');

VsCode 中的类型提示系统将 el.style 标记为 Element 中缺失。我可以解决这个问题:

/** @type {NodeListOf<HTMLElement>} */
const things = document.querySelectorAll('.thing');
things.forEach(el => el.style.color = 'red');

为了让 VsCode 的类型系统满意而创建 var 似乎是错误的。

如果我使用打字稿,我想我可以做到

document.querySelectorAll<HTMLElement>('.thing') // etc...

有没有办法告诉 VsCode 的类型系统我希望从泛型方法中得到哪种类型?

您可以为此使用 jsdoc cast

// @ts-check
(/** @type {NodeListOf<HTMLElement>} */ (document.querySelectorAll('.thing'))).forEach(el => el.style.color = 'red');

请注意,您必须将转换的目标 ((document.querySelectorAll('.thing')) 括在括号中,以便该类型适用于正确的表达式。