Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using flow with document.querySelector

Tags:

dom

flowtype

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.

like image 232
Matthew Lehner Avatar asked May 09 '26 08:05

Matthew Lehner


1 Answers

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.

like image 69
loganfsmyth Avatar answered May 12 '26 08:05

loganfsmyth