I'm new to Flow and am having a bit of trouble assigning to DOM Element types properly.
Looking at the DOM declarations in the Flow repo, it feels like I'm missing something.
// Works
const otherMeta:?HTMLMetaElement = document.querySelector("meta");
//Doesn't work
const metaTag:?HTMLMetaElement = document.querySelector("meta[name='something']");
The second example results in the following error:
const metaTag:?HTMLMetaElement = document.querySelector("meta[name='something']");
^ HTMLElement. This type is incompatible with
const metaTag:?HTMLMetaElement = document.querySelector("meta[name='something']");
^ HTMLMetaElement
Have a look at the example in the Try Flow REPL tool.
Flow is not smart enough to know what the return type will be for an arbitrary querySelector query. The simple element-name queries have been hard-coded into the builtin type definitions. You can see them in Flow's Github repo.
For Flow to know that the result is an HTMLMetaElement, you'll need to explicitly verify that with code like
const metaTag: ?HTMLElement = document.querySelector("meta[name='something']");
if (metaTag && !(metaTag instanceof HTMLMetaElement)) throw new Error("Expected a 'meta' element.");
// use metaTag here
so by explicitly checking instanceof, Flow will recognize that metaTag must now be the type HTMLMetaElement. This type of behavior is very common in Flowtype and is referred to as refining the type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With