I'm currently trying to create a Service Worker with TypeScript and WorkBox. The following is my current WorkBox definition (just to get something going). How could I solve the type error that I explain the following?
In the registerRoute
piece TypeScript compiler tells that matchPrecache
expect two parameters, the other being of type HeadersInit
. If it is not given, default Content-Type: text/html
is assumed. I would like to be explicit and give the type, but when I do so, I get an error the matchPrecache
return value is not assignable.
If I check strategy.d.ts, it looks like so
/**
* A shortcut to create a strategy that could be dropped-in to Workbox's router.
*
* On browsers that do not support constructing new `ReadableStream`s, this
* strategy will automatically wait for all the `sourceFunctions` to complete,
* and create a final response that concatenates their values together.
*
* @param {Array<function({event, request, url, params})>} sourceFunctions
* An array of functions similar to {@link module:workbox-routing~handlerCallback}
* but that instead return a {@link module:workbox-streams.StreamSource} (or a
* Promise which resolves to one).
* @param {HeadersInit} [headersInit] If there's no `Content-Type` specified,
* `'text/html'` will be used by default.
* @return {module:workbox-routing~handlerCallback}
* @memberof module:workbox-streams
*/
declare function strategy(sourceFunctions: StreamsHandlerCallback[], headersInit: HeadersInit): RouteHandlerCallback;
export { strategy };
import { clientsClaim, skipWaiting } from 'workbox-core';
import { strategy as streamsStrategy } from 'workbox-streams';
import { cleanupOutdatedCaches, matchPrecache, precacheAndRoute } from "workbox-precaching";
import { registerRoute } from "workbox-routing";
declare const self: any;
self.addEventListener("message", (event: { data: any; type: any; ports: any }) => {
if (event.data && event.data.type === "SKIP_WAITING") {
self.skipWaiting();
}
});
precacheAndRoute(self.__WB_MANIFEST);
cleanupOutdatedCaches();
const requestHeaders: HeadersInit =
{
"Content-Type": "text/html"
}
registerRoute(
'/', streamsStrategy([() => matchPrecache("index.html")], requestHeaders)
);
skipWaiting();
clientsClaim();
Edit : All right! When I'm not just looking at VS Code error but try to build, I discovered a bunch of other errors in the command line. One long piece of text
node_modules/typescript/lib/lib.dom.d.ts:25:1 - error TS6200: Definitions of the following
identifiers conflict with those in another file: EventListenerOrEventListenerObject,
ImportExportKind, TableKind, ValueType,
ExportValue, Exports, ImportValue, ModuleImports,
Imports, name, ==> HeadersInit <==, BodyInit, RequestInfo, BlobPart, DOMHighResTimeStamp, CanvasImageSource, OffscreenRenderingContext, MessageEventSource,
ImageBitmapSource, OnErrorEventHandler, TimerHandler, PerformanceEntryList, ReadableStreamReadResult, VibratePattern, AlgorithmIdentifier, HashAlgorithmIdentifier, BigInteger, NamedCurve,
GLenum, GLboolean, GLbitfield, GLint, GLsizei, GLintptr, GLsizeiptr, GLuint, GLfloat, GLclampf, TexImageSource, Float32List, Int32List, GLint64, GLuint64, Uint32List, BufferSource, DOMTimeStamp,
FormDataEntryValue, IDBValidKey, Transferable, BinaryType, CanvasDirection, CanvasFillRule, CanvasLineCap, CanvasLineJoin, CanvasTextAlign, CanvasTextBaseline, ClientTypes, ColorSpaceConversion, EndingType, IDBCursorDirection, IDBRequestReadyState, IDBTransactionMode, ImageOrientation, ImageSmoothingQuality, KeyFormat, KeyType, KeyUsage, NotificationDirection, NotificationPermission, OffscreenRenderingContextId, PermissionName, PermissionState, PremultiplyAlpha, PushEncryptionKeyName, PushPermissionState, ReferrerPolicy, RequestCache, RequestCredentials, RequestDestination, RequestMode, RequestRedirect, ResizeQuality, ResponseType, ServiceWorkerState, ServiceWorkerUpdateViaCache, VisibilityState, WebGLPowerPreference, WorkerType, XMLHttpRequestResponseType
I tried to emphasize one of them is this problematic HeadersInit
. My tsconfig.json
is as follows
{
"compilerOptions": {
"target": "esnext",
"module": "esnext",
"moduleResolution": "node",
"noEmitOnError": true,
"lib": ["esnext", "dom"],
"strict": true,
"esModuleInterop": false,
"allowSyntheticDefaultImports": true,
"experimentalDecorators": true,
"importHelpers": true,
"outDir": "out-tsc",
"sourceMap": true,
"inlineSources": true,
"forceConsistentCasingInFileNames": true,
"removeComments": true,
"rootDir": "./"
},
"include": ["**/*.ts"]
}
and in my package.json
I have
"@types/workbox-sw": "^4.3.1",
"@types/workbox-window": "^4.3.3",
so maybe this has something to do with this.
Edit 2 : That previous error happens only if I put
/// <reference lib="webworker" />
on top of the file. After removing it I get a same problem as described at WorkBox issue #2584 (as far as error messages go).
Edit 3 : I removed the explicit reference, found WorkBox issue #2172 and tried adding this library to tsconfig.json
and now there are again a lot of messages about type conflicts between dom
and webworker
library definitions.
Edit 4 : I noticed https://github.com/microsoft/TypeScript/issues/20595 and consequently also TypeScript: Declare Different Libraries/References for Different Files Within the Same Project about the TypeScript dom
and webworker
library conflict. It appears removing webworker
from tsconfig.json
does not fix the original problem with streamsStrategy
and HeadersInit
.
Try to create separate folder for you service worker and extend main tsconfig.json for this folder. To do this, you need create another tsconfig.json inside folder with your serviceworker.ts, with next content:
{
"extends": "../tsconfig.json",
"compilerOptions": {
"noEmit": false
},
"lib": ["webworker"],
"include": ["."]
}
And, I hope, you know, that service worker must compile to separate file as webworker. Can you provide link to your project?