Can you share the appropriate tsconfig.json configuration for a service worker implementation?

Simply put: TypeScript's lib: ['DOM'] does not incorporate Service Worker types, despite @types/service_worker_api indicating otherwise.

I have a functional TypeScript service worker. The only issue is that I need to use // @ts-nocheck at the beginning of the file because TypeScript struggles with the service worker types.

In line with guidance from TypeScript type definitions for ServiceWorker, I initially followed the steps to install types for service_worker_api:

$ npm install --save @types/service_worker_api

npm WARN deprecated @types/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4d3e283f3b242e28123a223f26283f122c2c240d7d637d6374">[email protected]</a>: ServiceWorker types are now provided by '--lib dom'

Therefore, I adjusted my tsconfig as follows:

{
  "compilerOptions": {
    "rootDir": "src",
    "composite": true,
    "module": "es2020",
    "moduleResolution": "Node",
    // Output files will be in dist/service-worker.js
    "outDir": "dist",
    // From "@types/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0c7f697e7a656f69537b637e67697e536c66455c55674719">[email protected]</a>: ServiceWorker types are now provided by '--lib dom'"
    "lib": ["DOM"]
  },
  "include": ["src/service-worker.ts"]
}

This results in an error:

$ npx tsc --project tsconfig.serviceworker.json
src/service-worker.ts(27,34): error TS2339: Property 'clients' does not exist on type 'Window & typeof globalThis'.
src/service-worker.ts(51,8): error TS2339: Property 'skipWaiting' does not exist on type 'Window & typeof globalThis'.

I also experimented with WebWorker - even though WebWorker differs from a service worker - and encountered this failure:

src/service-worker.ts(66,56): error TS2339: Property 'data' does not exist on type 'Event'.
src/service-worker.ts(67,23): error TS2339: Property 'data' does not exist on type 'Event'.

What is the appropriate tsconfig.json for a service worker?

Answer №1

Sharing knowledge for those facing similar challenges

In the quest for current information, I stumbled upon Joshua T's enlightening blog post Strongly Typed Web and Service Workers with TypeScript.

  • It is worth noting that TypeScript does come with service workers by default (refer to lib.webworker.d.ts)
  • As rightly pointed out by Josh:

There are certain unresolved issues related to Web Worker types causing hurdles in achieving robust type-checking for service worker files.

Opting for 'Solution B: TSConfig Libs' - indeed, utilize 'WebWorker':

{
  "compilerOptions": {
    "rootDir": "src",
    "composite": true,
    "module": "es2020",
    "moduleResolution": "Node",
    // The resulting files will be located in dist/service-worker.js
    "outDir": "dist",
    // As per https://joshuatz.com/posts/2021/strongly-typed-service-workers/
    "lib": ["WebWorker", "ES2015"]
  },
  "include": ["src/service-worker.ts"]
}

Note that since VSCode supports only a single tsconfig.json per project, you may still have to include @ts-ignore in certain lines.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for accessing HttpParams within a WebApi Controller while utilizing the [HttpPut] method

I am attempting to update a specific resource by accessing it through the PUT method in an Angular service. RollBackBatchById(selectedBatchId: number) { const params = new HttpParams(); params.append('resourceId', resourceId.toString()); ...

Leveraging the power of map in an Angular typescript file

I've been attempting to populate a Map in Angular by setting values dynamically. When certain buttons are clicked, the onClick function is invoked. typeArray: Map<number,string>; Rent(movieId: number){ this.typeArray.set(movieId,"Rental ...

Creating a custom `onSubmit` function with Formik, TypeScript, and hooks can be a powerful way

I'm currently creating form onSubmit functions utilizing the useCallback hooks specifically designed for use with the formik library. A sample structure of my component using formik would be as follows: import { useContactForm } from './useCon ...

What is the reason that property spreading is effective within Grid components but not in FormControl components?

Explore the sandbox environment here: https://codesandbox.io/s/agitated-ardinghelli-fnoj15?file=/src/temp4.tsx:0-1206. import { FormControl, FormControlProps, Grid, GridProps } from "@mui/material"; interface ICustomControlProps { gridProps?: ...

Angular 2 or more variable binding

In this demonstration, only the unit-object will be saved: <select id="unit" name="unit" #unit="ngModel" class="form-control" [(ngModel)]="iu.unit" (change)="onDropdownChangeUnit($event)"> <option *ngFor="let i of UI_Units" [ngV ...

Guide on efficiently inserting values into an array of objects

I'm looking to extract specific values from the enum below enum p { XDR = 1, PT1M = 2, PT1M_ = 2, PT5M = 3, PT5M_ = 3, PT15M = 4, PT15M_ = 4, PT1H = 5, PT1H_ = 5, P1D = 6, P1D_ = 6, P7D = 7, P1W = 7, ...

Creating a nested type using template literal syntax

Given a two-level nested type with specific properties: export type SomeNested = { someProp: { someChild: string someOtherChild: string } someOtherProp: { someMoreChildren: string whatever: string else: string } } I am looking ...

The absence of the @Injectable annotation is causing an issue when importing a JSON

I am currently in the process of integrating a JSON file into my service by using a @inject() tag within the constructor. Below is the code snippet I am working with. DependencyInjectionContainer.ts import { Container, decorate, injectable } from "invers ...

How can you typically verify the type of an object variable in TypeScript?

How can I verify if the obj variable contains all the properties defined in the Person interface? interface Person { name: string; age: number; } const jsonObj = `{ name: "John Doe", age: 30, }`; const obj: Person = JSON.parse(jsonObj); ...

Error message is not shown by React Material UI OutlinedInput

Using React and material UI to show an outlined input. I can successfully display an error by setting the error prop to true, but I encountered a problem when trying to include a message using the helperText prop: <OutlinedInput margin="dense&quo ...

Check the validity of a password using Angular's reactive forms

For my password validation using ng Reactive Forms, I have a basic html input field for the password and warning paragraphs outlining the password requirements. <div class="field"> <label class="label">Password</label ...

The specified type cannot be assigned to the type 'IntrinsicAttributes & MoralisProviderProps'

I'm brand new to TypeScript and I have a question about setting initializeOnMount to true. Why does it only allow me to set it to false? Here is the error message: Type '{ children: Element; appId: string | undefined; serverUrl: string | undefine ...

How can I prevent Intellisense from automatically importing all global variables from Mocha (or any other testing library) into files that are not designated for testing purposes?

I am managing these files in the same directory. package.json: { "name": "example", "version": "1.0.0", "devDependencies": { "@types/mocha": "^7.0.1", "@types/node": "^13.7.1" } } tsconfig.json: {} index.ts: export const test = () =&g ...

Inter-component communication within nested structures in Angular 2

Working on an Angular2 project that involves multiple nested components, I have successfully sent data from a child component to its immediate parent. However, when dealing with three levels of nesting, the question arises: How can I send or modify data ac ...

Tips for updating parameters that are defined in a controller within a promise

Currently, I am developing a single page application using Angular and TypeScript. I am facing an issue with updating the parameter value (_isShowFirst) of the controller inside a promise function. It seems like nothing is recognized within the promise blo ...

Exporting ExpressJS from a TypeScript wrapper in NodeJS

I've developed a custom ExpressJS wrapper on a private npm repository and I'm looking to export both my library and ExpressJS itself. Here's an example: index.ts export { myExpress } from './my-express'; // my custom express wrap ...

Aligning the React Navigation header component's bottom shadow/border width with the bottom tabs border-top width

Currently, I am working on achieving a uniform width for the top border of the React Navigation bottom tabs to match that of the top header. Despite my efforts, I am unable to achieve the exact width and I am uncertain whether it is due to the width or sha ...

Looking to retrieve HTML elements based on their inner text with queryselectors?

I am looking to extract all the HTML divs that contain specific HTML elements with innerText = ' * ' and save them in an array using Typescript. If I come across a span element with the innerText= ' * ', I want to add the parent div to ...

Setting up event listeners from a string array (using PIXI.js)

Hey there! I've encountered a bit of an interesting challenge that could easily be resolved by duplicating the code, but where's the fun in that? This project is more of an experiment for me, just to prove that I can do it. However, the idea has ...

Angular's forEach function seems to be stuck and not loop

I'm attempting to cycle through a list of objects in my Angular/Typescript code, but it's not working as expected. Here is the code snippet: businessList: RemoteDataSet<BusinessModel>; businessModel: BusinessModel; this.businessList.forE ...