我正在尝试将 Firebase Firestore
withConverter()
方法用于 JavaScript 版本 9 SDK。
我的代码改编自本教程。
基本思想是我们可以使用
withConverter()
为Firestore文档数据添加TypeScript类型。
我的代码和教程之间的主要区别是教程使用
import { firestore } from "firebase-admin"
和 firestore().collection()
来自安全环境的 Admin SDK。当我在前端使用import { collection } from 'firebase/firestore';
达到相同的效果时。
我的问题是我的代码抛出 TypeScript 错误。
这是我的代码:
import { initializeApp } from 'firebase/app';
import { collection, getFirestore, PartialWithFieldValue, QueryDocumentSnapshot } from 'firebase/firestore';
// Firestore setup
const firebaseConfig = {
...
};
const firebaseApp = initializeApp(firebaseConfig);
const firestore = getFirestore(firebaseApp);
// Making the converter
const converter = <T>() => ({
toFirestore: (data: PartialWithFieldValue<T>) => data,
fromFirestore: (snap: QueryDocumentSnapshot) => snap.data() as T,
});
// This works without error, "userColRef" is correctly typed as "CollectionReference<User>"
const userColRef = collection(firestore, 'users').withConverter(converter<User>());
// This throws an error
const dataPoint = <T>(collectionPath: string) => {
return collection(firestore, collectionPath).withConverter(converter<T>()); // <-- ERROR HERE
};
这是
converter<T>()
上的 TypeScript 错误:
No overload matches this call. Overload 1 of 2, '(converter: null): CollectionReference<DocumentData>', gave the following error.
Argument of type '{ toFirestore: (data: PartialWithFieldValue<T>) => PartialWithFieldValue<T>; fromFirestore: (snap: QueryDocumentSnapshot) => T; }' is not assignable to parameter of type 'null'. Overload 2 of 2, '(converter: FirestoreDataConverter<T>): CollectionReference<T>', gave the following error.
Argument of type '{ toFirestore: (data: PartialWithFieldValue<T>) => PartialWithFieldValue<T>; fromFirestore: (snap: QueryDocumentSnapshot) => T; }' is not assignable to parameter of type 'FirestoreDataConverter<T>'.
The types returned by 'toFirestore(...)' are incompatible between these types.
Type 'PartialWithFieldValue<T>' is not assignable to type 'DocumentData'.
Type 'T extends Primitive ? T : T extends {} ? { [K in keyof T]?: FieldValue | PartialWithFieldValue<T[K]> | undefined; } : never' is not assignable to type 'DocumentData'.
Type 'T | (T extends {} ? { [K in keyof T]?: FieldValue | PartialWithFieldValue<T[K]> | undefined; } : never)' is not assignable to type 'DocumentData'.
Type 'Primitive & T' is not assignable to type 'DocumentData'.
Type 'undefined & T' is not assignable to type 'DocumentData'.ts(2769)
关于
withConverter()
的更多细节可以在这里的官方文档中找到。