将流与 document.querySelector 一起使用

Mat*_*ner 3 dom flowtype

我是 Flow 的新手,在正确分配给 DOM 元素类型时遇到了一些麻烦。

查看Flow 存储库中的DOM 声明,感觉好像我错过了一些东西。

// Works 
const otherMeta:?HTMLMetaElement = document.querySelector("meta");

//Doesn't work
const metaTag:?HTMLMetaElement = document.querySelector("meta[name='something']");
Run Code Online (Sandbox Code Playgroud)

第二个示例导致以下错误:

const metaTag:?HTMLMetaElement = document.querySelector("meta[name='something']");
                                 ^ HTMLElement. This type is incompatible with
const metaTag:?HTMLMetaElement = document.querySelector("meta[name='something']");
               ^ HTMLMetaElement
Run Code Online (Sandbox Code Playgroud)

查看Try Flow REPL 工具中的示例

log*_*yth 5

Flow 不够聪明,无法知道任意querySelector查询的返回类型是什么。简单的元素名称查询已被硬编码到内置类型定义中。你可以在Flow 的 Github repo 中看到它们。

为了让 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
Run Code Online (Sandbox Code Playgroud)

因此通过显式检查instanceof,Flow 将识别出现在metaTag 必须是类型HTMLMetaElement。这种类型的行为在 Flowtype 中非常常见,称为细化类型。