I tried to typecheck a script that is normally run in a webworker context. importScripts works but postMessage fails. How do I tell flow that postMessage is valid in that context?
My recommendation would be to do:
declare var self: DedicatedWorkerGlobalScope;
And then use self.onmessage, self.importScripts, self.postMessage, etc. self is the global object in a web worker. The line above should tell Flow what type the variable this. DedicatedWorkerGlobalScope is a type already built into Flow and it defines importScripts, postMessage, etc.
That said, it'd be nice if we could tell Flow which environment a given piece of code is expected to run in, e.g. Node, browser, web worker, etc. so that it can define the right globals (and only those!). @gabelevi @samwgoldman @mroch what do guys think of optionally expanding the @flow pragma to allow environment specs, e.g. @flow env=node which would only enable the built-in core and node library definitions?
Right, in my proposal, you'd be able to say @flow env=node,browser or @flow env=node,react or @flow env=browser,webworker.
Just ran into an issue about the environment... in my case flow thought alert was defined (because of window.alert), but I hadn't defined it (in node).
Looking through the included type defs (https://github.com/facebook/flow/blob/7d700411a2ac83d4656e5d442e1c8a96f33341ff/lib/dom.js#L2982), you can see a whole bunch of 'unsafe' variable names that are included as part of a Browser, but don't necessarily exist in a node environment.
@philikon 's suggestion (or something similar in the .flowconfig) would be great to prevent my sort of mistake in the future
Just had the same problem as @BlooJeans but with a function named focus, which is available in the browser but not in node.
Most helpful comment
My recommendation would be to do:
And then use
self.onmessage,self.importScripts,self.postMessage, etc.selfis the global object in a web worker. The line above should tell Flow what type the variable this.DedicatedWorkerGlobalScopeis a type already built into Flow and it definesimportScripts,postMessage, etc.That said, it'd be nice if we could tell Flow which environment a given piece of code is expected to run in, e.g. Node, browser, web worker, etc. so that it can define the right globals (and only those!). @gabelevi @samwgoldman @mroch what do guys think of optionally expanding the
@flowpragma to allow environment specs, e.g.@flow env=nodewhich would only enable the built-incoreandnodelibrary definitions?