ProgramGuru

Web Workers with TypeScript

Web Workers with TypeScript — why it matters

Web Workers run scripts on a different thread, allowing CPU-intensive computation away from the browser's main UI thread. A worker has no access to document or window DOM elements; it communicates through postMessage and message events. Type the message protocol and use transferable data when large payloads make copying costly.

What you’ll learn

  • Explain web workers with typescript and the problem it solves.
  • Identify the relevant compile-time checks and runtime responsibilities.
  • Run the example, predict its output, and try a realistic modification.

Understand the mechanism

The calculate function is pure and can be tested before sending work to a worker. The browser example transfers a typed request message to worker.ts and handles its typed response.

Workers do not share arbitrary mutable JavaScript objects with the page and cannot directly update DOM nodes.

Follow the concept flow

Web Workers with TypeScript — concept flowMain UI thread → postMessage → worker → Worker posts resultWeb Workers with TypeScript1Main UI thread2postMessage → worker3Worker posts resultBrowser code needs browser APIs; Node code needs Node.js APIs.
Follow the responsibilities from input to checked result.

Run the primary TypeScript example

Save as web-workers.ts. The following program passed strict TypeScript compilation, and the displayed output was captured by executing its emitted JavaScript with Node.js 22.16.0.

TypeScript source

type WorkRequest = { jobId: number; values: number[] };
type WorkResult = { jobId: number; sum: number };
function calculate(request: WorkRequest): WorkResult {
  return { jobId: request.jobId, sum: request.values.reduce((a, b) => a + b, 0) };
}
console.log(calculate({ jobId: 4, values: [2, 3, 5] }));

Verified output

{ jobId: 4, sum: 10 }

Compile: npx tsc --strict --target es2022 --module commonjs web-workers.ts; run: node web-workers.js. For Node.js API examples, install @types/node first. For browser projects, use the browser-specific instructions below.

The example runs in Node.js 22.16.0; if it reads runtime environment details, your displayed values may differ.

Trace the result

The calculate function is pure and can be tested before sending work to a worker. The browser example transfers a typed request message to worker.ts and handles its typed response.

Predict what changes if you alter one input. Then run the code to compare your reasoning with the real output.

Build the real browser interaction

Real browser lab: This TypeScript targets actual DOM APIs and was successfully type-checked against the DOM library. It requires a browser; its runtime interaction was not simulated in Node.js. Save the two files together, compile the TypeScript, and serve this folder through a local HTTP server such as python3 -m http.server 8000 (especially important for modules and workers).

index.html

<!doctype html>
<html lang="en"><head><meta charset="utf-8"><title>TypeScript browser lab</title></head><body>
<h1 id="title">TypeScript lesson</h1><button id="action">Run</button><p id="output"></p>
<script type="module" src="./app.js"></script>
</body></html>

app.ts

type RequestMessage = { jobId: number; values: number[] };
type ResultMessage = { jobId: number; sum: number };
const worker = new Worker(new URL("./worker.js", import.meta.url), { type: "module" });
worker.addEventListener("message", (event: MessageEvent<ResultMessage>) => {
  const output = document.querySelector<HTMLElement>("#output");
  if (output) output.textContent = `${event.data.jobId}: ${event.data.sum}`;
  worker.terminate();
});
const request: RequestMessage = { jobId: 4, values: [2, 3, 5] };
worker.postMessage(request);

worker.ts

type RequestMessage = { jobId: number; values: number[] };
type ResultMessage = { jobId: number; sum: number };
self.addEventListener("message", (event: MessageEvent<RequestMessage>) => {
  const message = event.data;
  const response: ResultMessage = {
    jobId: message.jobId,
    sum: message.values.reduce((a, b) => a + b, 0),
  };
  self.postMessage(response);
});
export {};

Compile: npx tsc --strict --target es2022 --module es2022 --lib es2022,dom app.ts. For the worker example also compile worker.ts with --lib es2022,webworker. Then open the served HTML page in a browser to interact with it.

Common mistake and correction

Workers do not share arbitrary mutable JavaScript objects with the page and cannot directly update DOM nodes.

Identify whether the failure is a type-checking issue, a configuration issue, or a runtime behavior issue before choosing a fix.

Practice the concept

Make the worker return both sum and count, then update the page when its message arrives.

Write down your expected result first. For configuration examples, compare compiler output and diagnostics; for test examples, make the assertion fail deliberately to verify that the tool reports it.

Check your understanding

Which statement best describes the role of TypeScript and the actual runtime for this lesson?
Choose one answer. You can try again.

Answer and explanation

The described check or API works only within its stated environment and still needs the corresponding runtime behavior.

The calculate function is pure and can be tested before sending work to a worker. The browser example transfers a typed request message to worker.ts and handles its typed response.

What to remember

Web Workers run scripts on a different thread, allowing CPU-intensive computation away from the browser's main UI thread.

Run the primary example, then complete the practice task or environment-specific lab.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: TypeScript with Node.js →