5

Have Typescript project.

When this: postMessage(result);

I get this..

Expected 2-3 arguments, but got 1.Expected 2-3 arguments, but got 1.

When this: postMessage(result, '*');

I get this..

Uncaught TypeError: Failed to execute 'postMessage' on 'DedicatedWorkerGlobalScope': Overload resolution failed.
    at runParser

What does Typescript want here? Is it one or two arguments? And why is this causing an issue?

GN.
  • 8,672
  • 10
  • 61
  • 126
  • 1
    Well the first one is obviously wrong because it takes 2 or 3 parameters. See the docs at https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage. The second one should be `window.postMessage`, where `window` is the window you're posting to. – user2740650 Oct 18 '20 at 01:26
  • 1
    here is an example https://stackblitz.com/edit/typescript-post-message – Ericgit Oct 18 '20 at 01:28
  • 1
    This error happens in the worker scope, not the scope with Window – GN. Oct 18 '20 at 20:03
  • Right, sorry. That's definitely odd because 1 value is allowed in that case. I found a similar question that might help. https://stackoverflow.com/questions/47299899/failed-to-execute-postmessage-on-dedicatedworkerglobalscope-the-provided-va. – user2740650 Oct 19 '20 at 01:07
  • Oh, try navigating to `postMessage` in your editor (eg. ctrl-click in VSCode). I bet it's pointing to the version for the window object, not the worker version. That's why it's complaining I bet. Try being more explicit (I think the syntax is `self.postMessage(result)`). – user2740650 Oct 19 '20 at 01:52
  • Does this answer your question? [How do I strongly type a TypeScript web worker file with postMessage?](https://stackoverflow.com/questions/48950248/how-do-i-strongly-type-a-typescript-web-worker-file-with-postmessage) – Konrad May 27 '21 at 11:36

2 Answers2

3

If you are using MessageChannel's port postMessage function, then you have to pass only one parameter.

event.ports[0].postMessage(data)

If you are using window.postMessage, then you have to pass 2 or 3 parameters.

window.postMessage(data, origin, [transfer])
Joan PM
  • 31
  • 2
2

You're going to have to add webworker to your tsconfig.json or create a separate TS project for your worker, because postMessage has a different API in the worker and in the browser environment.

"compilerOptions" : {
    "lib": [
        "webworker"
Andor Polgar
  • 483
  • 3
  • 13
  • 1
    adding "webworker" clashed with "dom", to create a project with both i had to follow: https://stackoverflow.com/questions/56356655/structuring-a-typescript-project-with-workers – Stephen Apr 21 '22 at 13:04