Flow - 如何使用 getElementById 返回 HTMLInputElement 而不检查 instanceof?

hjk*_*kml 5 javascript types flowtype

如果我有一个<input>带有 id 的对象asdf,并且我运行const asdf = document.getElementById('asdf'),Flow 会假设它asdf是 anHTMLElement而不是 an HTMLInputElement。我需要asdf成为一个HTMLInputElement,这样 Flow 才会让我调用value它,因为value它不能保证存在于HTMLElements 上,但存在于HTMLInputElements 上。因此,为了使其工作,我必须检查if (asdf instanceof HTMLInputElement),然后运行我想要的代码。

有一个更好的方法吗?

小智 -3

如果“asdf”可以不是“input”,并且您需要确定:

const asdf = document.getElementById('asdf')

if (asdf.tagName === 'INPUT') {
    //your code...
}
Run Code Online (Sandbox Code Playgroud)