9
votes

I am using firebase cloud functions with javascript on cloud functions. And, I want to switch from javascript to typescript.

However I cannot use firebase-admin on typescript as following command failed.

command: npm install @types/firebase-admin --save-dev
error:  '@types/firebase-admin' is not in the npm registry.

According to this release note, it looks that firebase admin support typescript. Can somebody tell us how to use typescript with firebase-admin on cloud functions?

https://firebase.google.com/support/release-notes/admin/node#4.1.3

4

4 Answers

12
votes

You don't need to install an @types module, because firebase-admin ships with TypeScript support in the box. You should be able to use it with TypeScript just by installing firebase-admin.

import * as admin from 'firebase-admin';
5
votes

It seems that types are provided when imported using ES6 Modules:

  1. tsconfig.json
{
    "compilerOptions": {
        "resolveJsonModule": true,               // json imports
        "esModuleInterop": true,                 // import common modules as ES6 Modules
        "allowSyntheticDefaultImports": true,    // support typesystem compatibility
    }
}
  1. index.ts
import firebase from 'firebase-admin';
import serviceAccount from './service-account.json';

const params = {               //clone json object into new object to make typescript happy
    type: serviceAccount.type,
    projectId: serviceAccount.project_id,
    privateKeyId: serviceAccount.private_key_id,
    privateKey: serviceAccount.private_key,
    clientEmail: serviceAccount.client_email,
    clientId: serviceAccount.client_id,
    authUri: serviceAccount.auth_uri,
    tokenUri: serviceAccount.token_uri,
    authProviderX509CertUrl: serviceAccount.auth_provider_x509_cert_url,
    clientC509CertUrl: serviceAccount.client_x509_cert_url
}

firebase.initializeApp({
    credential: firebase.credential.cert(params),
})
0
votes

For those who are still struggling, reloading VSCode after installing firebase-admin did the work for me.

0
votes

I know i'm late but I found another way to do this, using the answer given by Peter:

  1. tsconfig.json
{
    "compilerOptions": {
        "resolveJsonModule": true,               // json imports
        "esModuleInterop": true,                 // import common modules as ES6 Modules
        "allowSyntheticDefaultImports": true,    // support typesystem compatibility
    }
}
  1. index.ts
import firebase from 'firebase-admin';
import serviceAccount from './service-account.json';

firebase.initializeApp({
    credential: firebase.credential.cert(serviceAccount as any), //Cast as any instead of clone the JSON.
})