"Cannot find name 'ServiceWorkerRegistration'" error when creating a firebase cloud function using Typescript
If like me you actually need to use the client firebase module inside a cloud function, the problem, along with a work-around, is described in #880:
A workaround is to add
"dom"
to the"lib"
compiler option in yourtsconfig.json
Our packages assume that DOM types exist. The problem is that importing
firebase/app
imports typings of all packages.Some of our packages (like Messaging) only work in the browser. These packages (or their types) should not be imported in a Node environment.
Edit: here is a safer answer that was posted in the issue thread
The suggested/promoted workaround here of adding "dom" to compilerOptions.lib is NOT safe. That would be telling the compiler that any and all dom type references are valid in my code, which is clearly not the case since Node.js is not a browser environment. If this library is meant to be used as a Node.js TypeScript library, then it should not depend on ambient dom-specific type definitions. A safer workaround for TypeScript 3.0 users is to import firebase as follows:
/// <reference lib="dom" />
import * as firebase from 'firebase';
That first line is a "triple-slash lib directive" (https://www.typescriptlang.org/docs/handbook/triple-slash-directives.html) first available in TypeScript 3.0. It's like adding dom to compilerOptions.lib but only for that one file. Note that the triple-slash directive must appear before any statements or it gets interpreted as just a normal comment.
I've run into this problem several times in the past. You can try adding the following to your tsconfig.json:
tsconfig.json:
"files": [
"node_modules/typescript/lib/lib.es6.d.ts"
],
"exclude": [
"node_modules"
]
So your complete tsconfig.json should look as follows:
{
"compilerOptions": {
"lib": ["es6"],
"module": "commonjs",
"noImplicitReturns": true,
"outDir": "lib",
"sourceMap": true,
"target": "es6"
},
"compileOnSave": true,
"include": [
"src"
],
"files": [
"node_modules/typescript/lib/lib.es6.d.ts"
],
"exclude": [
"node_modules"
]
}