有了tsconfig.json,

{

    "compilerOptions": {

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

    ]
  }


folder structure



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'
});


如何将消息字符串发布到sharedworker?

最佳答案

这是TypeScript中SharedWorker的工作示例。

来电者

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

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

worker.port.postMessage('Message');


工人

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中提取的类型定义的一部分。我将提交请求请求以对其进行更新。

关于javascript - 使用Sharedworker的帖子,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50641645/

10-11 23:30