为什么在使用Firebase Firestore的`withConverter()`时会出现这个TypeScript错误?

huangapple go评论64阅读模式
英文:

Why do I get this TypeScript error when using Firebase Firestore withConverter()?

问题

以下是要翻译的内容:

"I'm trying to use the Firebase Firestore withConverter() method for JavaScript Version 9 SDK.

My code is an adaptation of this tutorial.

The basic idea is that we can use withConverter() to add TypeScript typings for Firestore document data.

The main difference between my code and the tutorial is that the tutorial uses import { firestore } from "firebase-admin" and firestore().collection() which comes from the Admin SDK for secure environments. While I am using import { collection } from 'firebase/firestore'; to the same effect for the front end.

And my problem is that my code is throwing a TypeScript error.

Here's my code:

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
};

Here is the TypeScript error on converter<T>():

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)

More details about withConverter() can be found here in the offical docs.

英文:

I'm trying to use the Firebase Firestore withConverter() method for JavaScript Version 9 SDK.

My code is an adaptation of this tutorial.

The basic idea is that we can use withConverter() to add TypeScript typings for Firestore document data.

The main difference between my code and the tutorial is that the tutorial uses import { firestore } from "firebase-admin" and firestore().collection() which comes from the Admin SDK for secure environments. While I am using import { collection } from 'firebase/firestore'; to the same effect for the front end.

And my problem is that my code is throwing a TypeScript error.

Here's my code:

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
};

Here is the TypeScript error on converter<T>():

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)

More details about withConverter() can be found here in the offical docs.

答案1

得分: 2

I figured it out.

I added a new WithId intersection type because I am also using VueFire and it adds a new id property to all documents. Having this solved the issue above, although I'm not exactly sure why the error went away. But it's gone now.

I also updated fromFirestore: (snap: QueryDocumentSnapshot) => snap.data() as T to the more correct fromFirestore: (snap: QueryDocumentSnapshot<T>) => snap.data().

Here is the full code:

type WithId<T> = T & { id: string };

const converter = <T>() => ({
  toFirestore: (data: PartialWithFieldValue<T>) => data,
  fromFirestore: (snap: QueryDocumentSnapshot<T>) => snap.data(),
});

const dataPoint = <T>(collectionPath: string) => {
  return collection(firestore, collectionPath).withConverter(
    converter<WithId<T>>()
  );
};

UPDATE:

If you don't want to use WithId<T> it can also be done like this:

const converter = <T>(): FirestoreDataConverter<T> => ({
  toFirestore: (data: PartialWithFieldValue<T>) => data as DocumentData,
  fromFirestore: (snap: QueryDocumentSnapshot<DocumentData>) =>
    snap.data() as T,
});

const dataPoint = <T>(collectionPath: string) => {
  return collection(firestore, collectionPath).withConverter(
    converter<T>()
  );
};

This also works:

const converter = <T>() => ({
  toFirestore: (data: PartialWithFieldValue<T>) => data,
  fromFirestore: (snap: QueryDocumentSnapshot<T>) => snap.data(),
});

const dataPoint = <T extends DocumentData>(collectionPath: string) => {
  return collection(firestore, collectionPath).withConverter(
    converter<T>()
  );
};
英文:

I figured it out.

I added a new WithId intersection type because I am also using VueFire and it adds a new id property to all documents. Having this solved the issue above, although I'm not exactly sure why the error went away. But it's gone now.

I also updated fromFirestore: (snap: QueryDocumentSnapshot) =&gt; snap.data() as T to the more correct fromFirestore: (snap: QueryDocumentSnapshot&lt;T&gt;) =&gt; snap.data().

Here is the full code:

type WithId&lt;T&gt; = T &amp; { id: string };

const converter = &lt;T&gt;() =&gt; ({
  toFirestore: (data: PartialWithFieldValue&lt;T&gt;) =&gt; data,
  fromFirestore: (snap: QueryDocumentSnapshot&lt;T&gt;) =&gt; snap.data(),
});

const dataPoint = &lt;T&gt;(collectionPath: string) =&gt; {
  return collection(firestore, collectionPath).withConverter(
    converter&lt;WithId&lt;T&gt;&gt;()
  );
};

UPDATE:

If you don't want to use WithId&lt;T&gt; it can also be done like this:

const converter = &lt;T&gt;(): FirestoreDataConverter&lt;T&gt; =&gt; ({
  toFirestore: (data: PartialWithFieldValue&lt;T&gt;) =&gt; data as DocumentData,
  fromFirestore: (snap: QueryDocumentSnapshot&lt;DocumentData&gt;) =&gt;
    snap.data() as T,
});

const dataPoint = &lt;T&gt;(collectionPath: string) =&gt; {
  return collection(firestore, collectionPath).withConverter(
    converter&lt;T&gt;()
  );
};

This also works:

const converter = &lt;T&gt;() =&gt; ({
  toFirestore: (data: PartialWithFieldValue&lt;T&gt;) =&gt; data,
  fromFirestore: (snap: QueryDocumentSnapshot&lt;T&gt;) =&gt; snap.data(),
});

const dataPoint = &lt;T extends DocumentData&gt;(collectionPath: string) =&gt; {
  return collection(firestore, collectionPath).withConverter(
    converter&lt;T&gt;()
  );
};

huangapple
  • 本文由 发表于 2023年3月8日 17:34:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/75671368.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定