I am developing browser code using Typescript. Some of my code I want to run in a web worker.
Other than writing separate script files, what I would like to achieve is to have a class which wraps the Webworker and provide a method run(method: Function, ...args: any[]). This method I could then pass a function together with the argument values to call the function with in the worker. I can make this work using the Blob object as explained here https://www.html5rocks.com/en/tutorials/workers/basics/#toc-inlineworkers
The problem I run into though, is that the function I pass to run could have calls to postMessage in its body, which is the postMessage of the web worker global scope, not the DOM global scope. Hence, Typescript complains, because both have a incompatible declaration.
Does anybody have a suggestion how this could possibly work?
Option 1
Cast postMessage inside the function body as
`(postMessage as any)('Hi from web worker')
but that is ugly.
Option 2
would be to turn this lib.dom.d.ts signature
declare function postMessage(message: any, targetOrigin: string, transfer?: any[]): void;
into
declare function postMessage(message: any, targetOrigin?: string, transfer?: any[]): void;
(see the question mark added)
But is there something better?