How to detect if executing on main thread vs worker
I put everything in one file to make it easier to show, but is checking for
self.window
the preferred way? or is there some value in Deno context?
Bonus question, how can you properly type self
when in a worker? That type casting is neither pretty nor accurate3 Replies
I wasn't able to find the answer to your question in the official Deno documentation. However, based on the code snippet you've provided, I can offer some general advice.
In the context of web workers, checking for
self.window
is a common way to determine if the current context is the main thread or a worker thread, as window
is typically only defined in the main thread. However, this is more of a web platform convention rather than something specific to Deno.
Regarding your bonus question about typing self
in a worker, the type casting you've used (self as unknown as Worker & { name?: string }
) is indeed not the most elegant solution. A more accurate typing might involve using the Deno.Worker
type or creating a more specific interface that extends the Worker
interface with the properties you expect to be present on self
within the worker context.
Please note that this advice is not based on the Deno documentation, and I would advise you to double-check the accuracy of this advice. It's always a good idea to consult the latest Deno documentation or the community for the most current best practices.To type check a worker, add these lines at the top:
Source: https://docs.deno.com/runtime/manual/advanced/typescript/types#type-checking-web-workers
Thank you, the helps a ton