2

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?

0

1 Answer 1

2

I ran into the same problem. Here are my options:

Option 3

// @ts-ignore
postMessage(result);

Option 4

const postMessageOnWorker = postMessage as (message: any) => void;
postMessageOnWorker(result);

When I put the second argument like postMessage(result, "*"), it caused runtime-error (at least on Chrome). So, the second argument is not optional, it shouldn't be there.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.