错误TS2554:预期2-3个参数,但得到1

时间:2018-05-18 00:01:19

标签: javascript typescript web-worker

给定tsconfig.json

{

    "compilerOptions": {

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

    ]
  }

folder structure

1)

以下代码(./project1/tstut.ts),

if(window.Worker){
  console.log('Workers are available');
}
....
let worker: Worker = new Worker('worker.js');
worker.postMessage('do some work')

如何解决以下打字稿错误?

Property 'Worker' does not exist on type 'Window'

2)

对于下面的工作人员代码(./project1/worker.ts),

self.addEventListener('message', (e) => {
    // console.log(e)
    if(e.data === 'do some work'){
        console.log('Worker is about to start some work');
        let count: number =0;
        for(let i: number=0; i<1000; i++){
            count += i;
        }
        self.postMessage({message:count});
    }

})

JS允许语法self.postMessage({message: count})

https://github.com/Microsoft/TypeScript/issues/582

鉴于scenario不符合我的情况。

如何解决postMessage()的以下错误?在运行tsc

Expecting 2-3 arguments, but got 1

1 个答案:

答案 0 :(得分:3)

工人不会住在窗户对象上。

public function __construct() {
    parent::__construct();
    $this->load->helper('url');
    $this->load->helper('form');
    $key = $this->input->post('key');

    if(!logged_in() || (logged_in() && $key=='')) {
      redirect('/');
      die;
    }
}

要解决您的webworker postMessage错误,请使用&#39; webworkers&#39; tsconfig中的lib或以下

if (typeof(Worker) !== "undefined") {
    // Yes! Web worker support!
    // Some code.....
} else {
    // Sorry! No Web Worker support..
}

您的代码示例

<强> tstut.js

const ctx: Worker = self as any;
...
ctx.postMessage({message:count});

worker.js (无需在此处检查工人支持)

if(typeof(Worker) !== 'undefined'){
    const worker = new Worker('worker.js');
    worker.postMessage('do some work');
    worker.addEventListener('message', function (e) {
        //console.log(e);
        console.log(e.data);
    });
}