如何避免类型转换,同时使用Firebase Admin与非Admin版Firestore?
问题
我正在实现一个新的Firebase函数,需要使用firebase-admin包。当前代码如下:
import { getFirestore } from 'firebase-admin/firestore'; import { Firestore } from 'firebase/firestore';
为了复用前端Firestore应用的代码,我不得不编写如下代码:
const adminFirestore: Firestore = getFirestore() as unknown as Firestore;
否则会触发以下类型错误:
Type 'Firestore' is missing the following properties from type 'Firestore': type, app, toJSONts(2739)
请问是否有办法避免这种强制类型转换?
解决方案
统一使用Admin端Firestore类型:不要混用前端和Admin SDK的类型,直接从
firebase-admin/firestore导入Admin版本的Firestore类型,这样类型会完全匹配,无需强制转换:import { getFirestore, Firestore } from 'firebase-admin/firestore'; const adminFirestore: Firestore = getFirestore();抽象通用操作接口:如果需要复用前端代码,不要让复用代码直接依赖具体的
Firestore实例类型,而是定义一个包含所需操作的通用接口,让前端和Admin端的Firestore实例都实现该接口。复用代码仅依赖抽象接口,与具体SDK解耦:// 定义通用操作接口 interface FirestoreOperations { getDocument(path: string): Promise<unknown>; setDocument(path: string, data: unknown): Promise<void>; // 添加你需要的其他操作 } // 前端实例适配 import { getFirestore as getClientFirestore } from 'firebase/firestore'; const clientFirestore: FirestoreOperations = { async getDocument(path) { const docRef = getClientFirestore().doc(path); const docSnap = await docRef.get(); return docSnap.data(); }, async setDocument(path, data) { const docRef = getClientFirestore().doc(path); await docRef.set(data); } }; // Admin端实例适配 import { getFirestore } from 'firebase-admin/firestore'; const adminFirestore: FirestoreOperations = { async getDocument(path) { const docRef = getFirestore().doc(path); const docSnap = await docRef.get(); return docSnap.data(); }, async setDocument(path, data) { const docRef = getFirestore().doc(path); await docRef.set(data); } }; // 复用代码仅依赖FirestoreOperations接口 async function fetchDocument(db: FirestoreOperations, path: string) { return await db.getDocument(path); }临时类型兼容方案(不推荐长期使用):如果需要快速兼容,可以通过TypeScript的类型别名或交叉类型处理,但存在类型风险:
import { getFirestore } from 'firebase-admin/firestore'; import { Firestore as ClientFirestore } from 'firebase/firestore'; type CompatibleFirestore = ClientFirestore & Pick<ReturnType<typeof getFirestore>, keyof ClientFirestore>; const adminFirestore: CompatibleFirestore = getFirestore() as CompatibleFirestore;
内容的提问来源于stack exchange,提问作者okhobb
相关产品推荐
相关产品推荐

