Dom 将流与document.querySelector一起使用
我是Flow新手,在正确分配DOM元素类型时遇到了一些问题 看着回购协议中的资金流,我感觉好像错过了什么Dom 将流与document.querySelector一起使用,dom,flowtype,Dom,Flowtype,我是Flow新手,在正确分配DOM元素类型时遇到了一些问题 看着回购协议中的资金流,我感觉好像错过了什么 // Works const otherMeta:?HTMLMetaElement = document.querySelector("meta"); //Doesn't work const metaTag:?HTMLMetaElement = document.querySelector("meta[name='something']"); 第二个示例导致以下错误: const m
// Works
const otherMeta:?HTMLMetaElement = document.querySelector("meta");
//Doesn't work
const metaTag:?HTMLMetaElement = document.querySelector("meta[name='something']");
第二个示例导致以下错误:
const metaTag:?HTMLMetaElement = document.querySelector("meta[name='something']");
^ HTMLElement. This type is incompatible with
const metaTag:?HTMLMetaElement = document.querySelector("meta[name='something']");
^ HTMLMetaElement
查看Try Flow REPL工具。Flow不够聪明,无法知道任意
查询选择器的返回类型。简单的元素名称查询已硬编码到内置类型定义中。你可以在里面看到它们
为了让流知道结果是一个HTMLMetaElement,您需要使用如下代码显式验证
const metaTag: ?HTMLElement = document.querySelector("meta[name='something']");
if (metaTag && !(metaTag instanceof HTMLMetaElement)) throw new Error("Expected a 'meta' element.");
// use metaTag here
因此,通过显式检查instanceof
,Flow将识别metaTag
现在必须是HTMLMetaElement
类型。这种类型的行为在Flowtype中非常常见,称为细化类型