使用 @ts-check 在 JS 文件中键入断言元素
Type assert an element in a JS file with @ts-check
我有一个带有 // @ts-check
指令的 JS 文件,使用 JSDoc 注释来表示类型。
问题是从 document
.
检索元素时无法通过类型检查
所以我们在 HTML:
<input id="myInput">...
当我在 JS 中获取此元素时,类型检查抛出错误:
// @ts-check
const myInput = document.getElementById('myInput');
myInput.value = 'foobar';
Property 'value' does not exist on type 'HTMLElement'
如果我用 JSDoc @type
注释指定预期的类型,那么也会引发错误:
// @ts-check
/** @type {HTMLInputElement} */
const myInput = document.getElementById('myInput');
myInput.value = 'foobar';
Type 'HTMLElement' is not assignable to type 'HTMLInputElement'.
Property 'accept' is missing in type 'HTMLElement'.
如果我在 TS 中,我可以使用 document.getElementById('myInput') as HTMLInputElement
告诉它我期望这种类型。
如何使用 @ts-check
在 JS 中执行此操作?
解决方法是在变量和检索之间放置 @type
声明,并添加 ()
.
像这样:
// @ts-check
const myInput = /** @type {HTMLInputElement} */ (document.getElementById('myInput'));
myInput.value = 'foobar';
这种语法相当笨拙和可怕,但他们closed the bug所以我猜上面的语法是官方处理这个问题的方法。
如果你想绝对确定,你可以使用运行时检查,这也会让 typescript 相信赋值是安全的。
const myInput = document.getElementById('myInput');
if (myInput instanceof HTMLInputElement) {
myInput.value = 'foobar';
}
我有一个带有 // @ts-check
指令的 JS 文件,使用 JSDoc 注释来表示类型。
问题是从 document
.
所以我们在 HTML:
<input id="myInput">...
当我在 JS 中获取此元素时,类型检查抛出错误:
// @ts-check
const myInput = document.getElementById('myInput');
myInput.value = 'foobar';
Property 'value' does not exist on type 'HTMLElement'
如果我用 JSDoc @type
注释指定预期的类型,那么也会引发错误:
// @ts-check
/** @type {HTMLInputElement} */
const myInput = document.getElementById('myInput');
myInput.value = 'foobar';
Type 'HTMLElement' is not assignable to type 'HTMLInputElement'.
Property 'accept' is missing in type 'HTMLElement'.
如果我在 TS 中,我可以使用 document.getElementById('myInput') as HTMLInputElement
告诉它我期望这种类型。
如何使用 @ts-check
在 JS 中执行此操作?
解决方法是在变量和检索之间放置 @type
声明,并添加 ()
.
像这样:
// @ts-check
const myInput = /** @type {HTMLInputElement} */ (document.getElementById('myInput'));
myInput.value = 'foobar';
这种语法相当笨拙和可怕,但他们closed the bug所以我猜上面的语法是官方处理这个问题的方法。
如果你想绝对确定,你可以使用运行时检查,这也会让 typescript 相信赋值是安全的。
const myInput = document.getElementById('myInput');
if (myInput instanceof HTMLInputElement) {
myInput.value = 'foobar';
}