如何让流程将 document.getElementById
的返回值解释为 HTMLInputElement
,而不是更通用的 HTMLElement
?
示例:
let input = document.getElementById('myinput');
console.log(input.value);
script.js:28
28: console.log(input.value);
^^^^^ property `value`. Property not found in
28: console.log(input.value);
^^^^^ HTMLElement
来自https://github.com/facebook/flow/blob/master/lib/dom.js
declare class Document extends Node {
…
getElementById(elementId: string): HTMLElement;
…
}
但是,getElementById
可能会返回子类(在本例中为 HTMLInputElement
)
declare class HTMLInputElement extends HTMLElement {
…
value: string;
…
}
我希望能够访问输入元素的 value
属性,而不会引发错误。
最佳答案
问题是 Flow 编译器事先不知道 HTMLElement input
变量的类型,它会抛出错误。
通常建议人们在这种情况下这样做:
var input = document.getElementById('myinput');
if (input instanceof HTMLInputElement) {
console.log(input.value);
}
在 dynamic type tests 中了解此技术文档部分。
关于javascript - 流类型: use extended class from function returning parent class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39427153/