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

Displaying data-table with only the values that are considered true

Right now, I am utilizing the AgReact table to exhibit data fetched from my endpoints. The data-table is functioning properly, however, it seems to be unable to display false values received from the endpoints on the table. Below are the snippets of my cod ...

There seems to be a malfunction with the routing feature in the src/index.html file

My routing setup is not functioning as expected in src/index.html angular. What I have is a header with some links for navigation: <header> <div class="logo"> <div class="logo-img-div"> <img src="../../ass ...

The rendering process in ag-grid is resulting in the service component initialized from an event to become null

Currently, I am utilizing ag-grid and need help understanding a specific issue. In my method for preparing GridOptions, I have set up an onCellValueChanged event that triggers a service component to access the database and populate the data. However, when ...

What is the best way to exclude React.js source files from a fresh Nest.js setup?

My setup includes a fresh Nest.js installation and a directory named "client" with a clean create-react-app installation inside. Here is the project structure: ./ ...some Nest.js folders... client <- React.js resides here ...some more Nest.js fo ...

Invoking a parent method from a child component in a TypeScript and React application

I'm facing an issue where I am unable to call a method from a parent component in my child component. The method in the parent element is not being triggered when the child component tries to call it. This problem is showcased in a simple example with ...

The issue arises when Jest fails to align with a custom error type while utilizing dynamic imports

In my project, I have defined a custom error in a file named 'errors.ts': export class CustomError extends Error { constructor(message?: string) { super(message); Object.setPrototypeOf(this, Error.prototype); this.nam ...

Retrieve a specific element from an array list

Hey everyone, I'm facing a problem in my application where I need to extract a specific value from my array and display it in a table for users to see. Check out the code snippet below: Here's my mock data: { "Data": "2020-0 ...

When using Vue with Vuetify, be aware that object literals can only specify known properties. In this case, the type 'vuetify' does not exist in the ComponentOptions of Vue with DefaultData

Started a fresh Vue project with TypeScript by following this guide: https://v2.vuejs.org/v2/guide/typescript.html If you don't have it installed yet, install Vue CLI using: npm install --global @vue/cli Create a new project and choose the "Manual ...

Ensure that only numbers with a maximum of two decimal places are accepted in Angular 2 for input

On my webpage, there are several input boxes where users can enter numbers. I need to prevent them from entering more than two decimal places. Although I tried using the html 5 input Step="0.00", it didn't work as expected. I am open to any TypeScri ...

I'm encountering an issue with one of my routes not loading correctly in Angular 4 Universal

I have been working on implementing Universal and I believe I've made significant progress. My project is built on this seed. However, when I run "npm start", only the /about and /contact pages render successfully. The /home page does not render at al ...

Writing Data to Google Cloud Firestore Map using NextJS and Typescript with nested objects

I could use some assistance. I'm developing an application using NextJS (React), TypeScript, and Google Cloud Firestore. Everything seems to be working fine so far. However, I'm facing an issue with storing the address and phone number in a neste ...

What is the best way to maintain the correct 'this' context for a function that is outside of the Vue

I'm struggling with my Vue component and encountering some errors. <script lang="ts"> import Vue from 'vue'; import { ElForm } from 'element-ui/types/form'; type Validator = ( this: typeof PasswordReset, rule: any, va ...

What causes a standard React component with a default render prop to not pass PropTypes validation successfully?

I'm currently working on a React component with a render-prop that has a generic type. To improve usability, I want to set a default value for the render-prop. The code is functioning correctly, but during type-checking, I encountered a warning regard ...

Can someone provide guidance on utilizing the map function to iterate through intricate components in TypeScript?

I am facing a challenge while trying to iterate through a complex object containing 'inner objects'. When using the map function, I can only access one level below. How can I utilize map and TypeScript to loop through multiple levels below? Whene ...

The data type 'string | undefined' cannot be assigned to the data type 'string' when working with .env variables

Trying to integrate next-auth into my nextjs-13 application, I encountered an error when attempting to use .env variables in the [...nextauth]/route.ts: Type 'string | undefined' is not assignable to type 'string'. https://i.stack.im ...

Changing an array into an object in JavaScript without rearranging the keys

I have a collection { 1: {id: 1, first: 1, last: 5} 2: {id: 2, first: 6, last: 10} 3: {id: 3, first: 11, last: 15} } My goal is to reverse the order of items without rearranging the keys so that it looks like this: { 1: {id: 3, first: 11, last: 15} 2: { ...

What could be causing the table to display empty when we are passing data to the usetable function?

Visit Codesandbox to view Table While the header appears correctly, I noticed something strange. When I console log the data props, it shows all the necessary data. However, when I try to console.log row, there doesn't seem to be any single object re ...

What is the best way to incorporate node modules into my tsconfig file?

I've taken some raw angular typescript components and packaged them into a private NPM module for sharing between various projects. Although I import these components like any other npm library, I encounter an error message when trying to serve my ap ...

Load Angular template dynamically within the Component decorator

I am interested in dynamically loading an angular template, and this is what I have so far: import { getHTMLTemplate } from './util'; const dynamicTemplate = getHTMLTemplate(); @Component({ selector: 'app-button', // templat ...

The presence of an Angular Element within an Angular application can lead to a problematic cycle of constant reloading,

, I am encountering issues with integrating Angular Elements as plugins into my Angular application. The problem arises when building the element with "--prod" - it functions properly with "ng serve" in my development setup but causes infinite reloading wh ...