Kacaii
Kacaii3mo ago

Workers: Property 'onmessage' dos not exist

Im learning how to create worker threads but deno-ts says: Property 'onmessage' does not exist on type 'Window & typeof globalThis'. Code
// worker.ts
self.onmessage = (message) => {
// TODO: Do something with the message?
};
// worker.ts
self.onmessage = (message) => {
// TODO: Do something with the message?
};
Am I missing some configuration?
7 Replies
ud2
ud23mo ago
Add these lines to the top of worker.ts.
/// <reference no-default-lib="true" />
/// <reference lib="deno.worker" />
/// <reference no-default-lib="true" />
/// <reference lib="deno.worker" />
And if you run deno check as part of your workflow, instead of deno check main.ts worker.ts, do deno check main.ts and deno check worker.ts separately, or there may be false negatives.
Kacaii
KacaiiOP3mo ago
Thank you! Also, in what part of the documentation I can search to learn more about those top level comments?
ud2
ud23mo ago
These are triple-slash directives. no-default-lib="true" means “don't include default libraries” (deno.window and deno.unstable in Deno's case), and lib="…" references the specified library. I just read that no-default-lib might get deprecated soon. If that happens, the alternative would be to set compilerOptions.lib to [] in deno.json, and add a reference to deno.window to all non-worker scripts.
Doctor 🤖
Doctor 🤖3mo ago
I know of a package that makes using workers easier, but it is a bit of self advertisement. 😛
ElectronicFreezer
im curious its also possible to do export const self = globalThis as unknown as Worker and then import self in workers but maybe a little cursed
Doctor 🤖
Doctor 🤖3mo ago
JSR
@doctor/thread - JSR
@doctor/thread on JSR: A wrapper API around the Web Worker API
Doctor 🤖
Doctor 🤖3mo ago
It's going to receive better typings soon™️

Did you find this page helpful?