Typescript: Web Worker Example

Created on 15 Nov 2015  路  3Comments  路  Source: microsoft/TypeScript

Is there any place I can find an example of writing a web worker in typescript? I have created a new file myworker.ts that looks like below:

/// <reference path="IWorkerMessages.ts" />
self.onmessage = (ev: MessageEvent) =>
{
    var data = <IWorkerIncoming>ev.data;


} 

// I get a compiler error while trying to define self.deserialize
self.deserialize = (data: IWorkerIncoming) =>
{

}

could the file be refactored to something like

class MyWorker implements Worker
{
}

_Edited by @DanielRosenwasser to add code fences._

Question

All 3 comments

Webworkers in TypeScript work the same as in JavaScript. The only thing in question is where to get the typings from, which is our lib.webworker.d.ts. Take a look at http://blog.scottlogic.com/2015/08/10/ts-vs-proj.html and #4855.

In the future, StackOverflow is a better venue for these types of questions - just as a heads up.

Thanks for the link. Actually I found it more confusing than helpful to be honest. I am not using any virtual projects. Further I am developing a single page app with no MVC. I do my compilation within VS and am not using command line. The problems I am struggling with are:

  • How to compile the web worker code into a separate js
  • Looking at examples of web workers, it seems the compiled js ought to look something like:
    self.onmessage = function()...
    but if I write a typescript file that implements the Worker interface, that is not the compiled js I will get.
    I posted here as I thought response would be faster (and it was, thanks :)

These sort of questions are probably better asked on Stack Overflow.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Roam-Cooper picture Roam-Cooper  路  3Comments

zhuravlikjb picture zhuravlikjb  路  3Comments

uber5001 picture uber5001  路  3Comments

kyasbal-1994 picture kyasbal-1994  路  3Comments

dlaberge picture dlaberge  路  3Comments