Typing Workers
Web Workers and Node worker threads talk through messages. TypeScript does not type postMessage by default beyond any. You add a protocol: a discriminated union for messages, and a typed wrapper around onmessage.
Detailed Explanation
A worker is another JavaScript isolate. You send values with postMessage. The values are structured-cloned (or transferred). There is no shared TypeScript heap. A type you import in both files is a shared description, not a shared object. If the two sides disagree, the clone still happens and the types lie.
The minimum useful protocol is a discriminated union:
type ToWorker =
| { type: "hash"; id: string; payload: string }
| { type: "cancel"; id: string };
type FromWorker =
| { type: "ok"; id: string; hash: string }
| { type: "err"; id: string; message: string };
Both the main thread and the worker import these types (from a third file with no runtime, or from a .ts file that only exports types). Main types worker.postMessage as (msg: ToWorker) => void by wrapping the worker. The worker types self.onmessage as (ev: MessageEvent<ToWorker>) => void. Replies go out as FromWorker.
MessageEvent<T> is generic. The default T is any. Writing MessageEvent<ToWorker> is an assertion about what the other side sent. It is not checked. A version mismatch between worker bundle and window bundle is a classic production bug. Keep the protocol in one module and bump a version field on the union if you ship long-lived workers.
Transferables (ArrayBuffer, MessagePort) have their own type in the second argument to postMessage. After transfer, the buffer is detached. The type will not model detachment; do not keep using the buffer on the sending side.
Node's worker_threads is the same idea with parentPort.postMessage and worker.on("message", ...). @types/node types the payload as any. Apply the same wrapper. Do not use eval / workerData as an untyped bag; give workerData a type and validate it at the start of the worker.
import.meta.url and new URL("./worker.ts", import.meta.url) are how bundlers hook workers. The types for that URL are stringly. The safety is the protocol, not the URL type.
For worker lifecycle and the event loop inside a worker, see JavaScript web workers. Here, the work is the message union and the wrappers.
Code Examples
1. A shared protocol (types only).
// 1. A shared protocol (types only).
export type ToWorker =
| { type: "ping"; id: string }
| { type: "echo"; id: string; text: string };
export type FromWorker =
| { type: "pong"; id: string }
| { type: "echoed"; id: string; text: string };2. A thin typed wrapper on the main thread.
// 2. A thin typed wrapper on the main thread.
import type { FromWorker, ToWorker } from "./protocol.js";
function send(worker: Worker, msg: ToWorker): void {
worker.postMessage(msg);
}
function listen(worker: Worker, handler: (msg: FromWorker) => void): void {
worker.addEventListener("message", (ev: MessageEvent<FromWorker>) => {
handler(ev.data);
});
}
const worker = new Worker(new URL("./worker.js", import.meta.url), { type: "module" });
listen(worker, (msg) => {
if (msg.type === "pong") console.log(msg.id);
});
send(worker, { type: "ping", id: "1" });3. Worker side — MessageEvent<ToWorker>.
// 3. Worker side — MessageEvent<ToWorker>.
import type { FromWorker, ToWorker } from "./protocol.js";
self.onmessage = (ev: MessageEvent<ToWorker>) => {
const msg = ev.data;
const reply: FromWorker =
msg.type === "ping"
? { type: "pong", id: msg.id }
: { type: "echoed", id: msg.id, text: msg.text };
self.postMessage(reply);
};Common Gotchas
`MessageEvent<T>` is an assertion
the clone can still be the wrong shape. Validate `type` and required fields if the worker is a trust boundary.
Functions and class instances do not survive structured clone
the type may say `User` but methods are gone. Send data, not instances.
Keep the protocol in one module both sides import
two copy-pasted unions will drift.
Transferring an `ArrayBuffer` detaches it
the type still says `ArrayBuffer`. Do not read it on the sender after transfer.