当使用 checkJS 在 Javascript 中启用类型检查时,如何强制执行类型?

问题描述 投票:0回答:1

在 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 是什么?

javascript typechecking checkjs
1个回答
0
投票

请参阅 @type JSDoc 参考

/**
 * @type {HTMLInputElement}
 */
const chatfield = document.querySelector("#chatinput");

或内联

const chatfield = /** @type {HTMLInputElement} */(document.querySelector("#chatinput"));
© www.soinside.com 2019 - 2024. All rights reserved.