denoland / deno

A modern runtime for JavaScript and TypeScript.
https://deno.com
MIT License
97.93k stars 5.39k forks source link

Type Checking Service Workers #15975

Open mfulton26 opened 2 years ago

mfulton26 commented 2 years ago

Type Checking Web Workers | Types and Type Declarations | Manual | Deno outlines option to type check web workers but I do not see clear instructions for doing this for service workers. The best I've been able to find so far by explicitly casting self:

/// <reference no-default-lib="true" />
/// <reference lib="webworker" />

(<ServiceWorkerGlobalScope & typeof globalThis> self)
  .addEventListener("fetch", (event) => {
    event.respondWith(new Response("hello"));
  });

Can a dedicated DTS for Service Workers be defined that defines self using ServiceWorkerGlobalScope instead of WorkerGlobalScope (e.g. "serviceworker" DTS that might even share some types with "webworker" DTS)? Alternatively some support for doing a type guard (e.g. if (self instanceof ServiceWorkerGlobalScope)) could be helpful if the types were define to narrow accordingly.

marcushultman commented 1 year ago
/// <reference no-default-lib="true"/>
/// <reference lib="webworker" />

declare const self: ServiceWorkerGlobalScope;

Is what I've resorted to now. Proper solution would be neat.