Search code examples
typescriptweb-worker

typescript webworker onmessage handler error


I can't get typescript to compile the simple code snippet below. Even if I set the parameter ev to be of type MessageEvent.

I have tried with typescript 2.8.3 and 2.9.0.

Error message

Error:(262, 22) TS2345: Argument of type '(ev: any) => void' is not assignable to parameter of type 'MessageEvent'. Property 'data' is missing in type '(ev: any) => void'.

code snipet

const worker = new Worker('./worker/render-worker.ts');
worker.onmessage((ev) => {
  console.log(ev.data);
});

tsconfig.json

{
  "compileOnSave": false,
  "compilerOptions": {
    "sourceMap": true,
    "inlineSourceMap": false,
    "inlineSources": false,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es6",
    "lib": [
      "es2017",
      "scripthost",
      "webworker",
      "dom"
    ]
  }
}

Solution

  • Replace this:

    worker.onmessage((ev) => {
      console.log(ev.data);
    });
    

    With this:

    worker.onmessage = (ev) => {
      console.log(ev.data);
    };