mascaliente mascaliente - 1 month ago 7x
Node.js Question

Handling typescript typings with eval

I am trying to write a definition file for the webworker-threads npm library. In their documentation it says that you can create a new worker as follows:

let worker = new Worker(function() {
this.postMessage('worker created');

The trick is that everything inside of that function that is used to construct the worker has access to the worker itself through a self variable. This is accomplished in their code by checking if the argument passed into
new Worker()
is a function, and if so calling eval on it. See here.

I'm wondering how to duplicate this with my typings. So far I have this, but it doesn't work:

export class Worker {
public onmessage: (event: any) => any;

public thread: Thread;

constructor(fn?: Worker | string); // <= Doesn't work because technically the function passed in isn't a worker, it just accesses the new Worker as if it were.

public postMessage(data: any): void;

public terminate(): void;

public addEventListener(type: string, cb: (event: any) => any): void;

public removeEventListener(type: string): void;

Rem Rem

In TypeScript 2.0 that in Release Candidate TS changelog now you can write:

constructor(fn?: (this: Worker) => any);

In older TypeScript versions I can recommend to cast this to Worker inside callback.