在启用checkJS的JavaScript中如何强制指定类型?
JavaScript中启用类型检查后的类型处理方案
当在VS Code中通过jsconfig.json启用checkJs类型检查后,要解决类似Property 'value' does not exist on type 'Element'的错误,有几种等效于TypeScript类型断言的写法:
JSDoc类型注释声明变量类型
直接在变量上方用JSDoc注释指定其类型,让VS Code识别正确的类型:/** @type {HTMLInputElement} */ const chatfield = document.querySelector("#chatinput"); console.log(chatfield.value);内联JSDoc类型断言
类似TypeScript的as语法,通过内联JSDoc注释直接断言查询结果的类型:const chatfield = /** @type {HTMLInputElement} */ (document.querySelector("#chatinput")); console.log(chatfield.value);类型守卫(更安全的方式)
通过运行时检查缩小变量类型范围,既满足类型检查要求,又避免断言可能带来的风险:const chatfield = document.querySelector("#chatinput"); if (chatfield instanceof HTMLInputElement) { console.log(chatfield.value); }
内容的提问来源于stack exchange,提问作者Kokodoko
相关产品推荐
相关产品推荐

