1

使用给定的 tsconfig.json,

{

    "compilerOptions": {

      "lib": ["es2015", "dom"]
    },
    "files": [
      "./1_webworker/tstut.ts",
      "./1_webworker/worker.ts"

    ]
  }

文件夹结构


npm install --save @types/sharedworker

在下面的代码中(来自./1_webworker/tstut.ts),

let worker: Worker = new Worker('worker.js');

使用 sharedworker 语法,声明:

let worker: SharedWorker.SharedWorker = new SharedWorker('worker.js');

但以下是错误。

worker.postMessage('do some work'); // Property 'postMessage' does not exist on type 'SharedWorker'

worker.addEventListener('message', (e) => {

  console.log(e.data); // Property 'data' does not exist on type 'Event'
});

如何向共享工作者发布消息字符串?

4

1 回答 1

4

这是SharedWorkerTypeScript 中的一个工作示例。

调用者.ts

let worker = new SharedWorker('worker.js');
worker.port.start();

worker.port.onmessage = function (e) {
    console.log('Caller Received:', e.data);
}

worker.port.postMessage('Message');

工人.ts

interface SharedWorkerGlobalScope {
    onconnect: (event: MessageEvent) => void;
}

const _self: SharedWorkerGlobalScope = self as any;

_self.onconnect = function (e) {
    var port = e.ports[0];

    port.addEventListener('message', function (e) {
        console.log('Worker Received', e.data);
        port.postMessage('Result');
    });

    port.start(); // Required when using addEventListener. Otherwise called implicitly by onmessage setter.
}

当前SharedWorkerGlobalScope是您从 npm 中提取的类型定义的一部分。我将提交一个拉取请求以尽快更新它。

于 2018-06-01T10:52:30.223 回答