在 VS Code 中,您可以使用此 jsconfig.json 文件启用 javascript 的类型检查:
{
"compilerOptions": {
"checkJs": true
}
}
这可行,但当 VS Code 无法确定类型时会出现类型错误。例如:
const chatfield = document.querySelector("#chatinput")
console.log(chatfield.value)
错误:
Property 'value' does not exist on type 'Element'.
在 Typescript 中你会这样做:
const chatfield = document.querySelector("#chatinput") as HTMLInputElement
相当于这个的 javascript 是什么?
请参阅 @type JSDoc 参考
/**
* @type {HTMLInputElement}
*/
const chatfield = document.querySelector("#chatinput");
或内联
const chatfield = /** @type {HTMLInputElement} */(document.querySelector("#chatinput"));