-
-
Save huafu/d9205b413f8b62c85412f52108707de2 to your computer and use it in GitHub Desktop.
Issue with firebase typings when sharing code between frontend and backend
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// INFO: this has been simplified a maximum just to show the underlying issue | |
import { database as rtdbClient } from 'firebase' | |
import { database as rtdbServer } from 'firebase-admin' | |
type Database = rtdbClient.Database | rtdbServer.Database | |
type DataSnapshot = rtdbClient.DataSnapshot | rtdbServer.DataSnapshot | |
interface User { | |
id: string | |
name: string | |
} | |
export default async function loadUser(db: Database, id: string): Promise<User|null> { | |
const snap:DataSnapshot = await db.ref(`users/public/${id}`).once('value') | |
// here `db.ref(...)` will give: [ts] Cannot invoke an expression whose type lacks a call signature. Type '((path?: string) => Reference) | ((path?: string | Reference) => Reference)' has no compatible call signatures. | |
return snap.exists() ? {id, ... snap.val()} : null | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// INFO: here is an alternative which is working... | |
// until you get methods calling methods... and needs huge amount of overloads | |
// AND for any method accepting a "shared" firebase type | |
import { database as rtdbClient } from 'firebase' | |
import { database as rtdbServer } from 'firebase-admin' | |
type DataSnapshot = rtdbClient.DataSnapshot | rtdbServer.DataSnapshot | |
interface User { | |
id: string | |
name: string | |
} | |
export default async function loadUser(db: rtdbClient.Database, id: string): Promise<User|null> | |
export default async function loadUser(db: rtdbServer.Database, id: string): Promise<User|null> | |
export default async function loadUser(db, id) { | |
const snap:DataSnapshot = await db.ref(`users/public/${id}`).once('value') | |
return snap.exists() ? {id, ... snap.val()} : null | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment