简体   繁体   English

Firestore 9 onSnapshot TypeScripot 错误:传播类型只能从 object 类型创建。 ts(2698)

[英]Firestore 9 onSnapshot TypeScripot error: Spread types may only be created from object types. ts(2698)

When calling the data() method inside a Firestore 9 onSnapshot function it returns an Object containing all fields in the document.在 Firestore 9 onSnapshot function 中调用data()方法时,它会返回包含文档中所有字段的 Object。

But in my code below there is a TypeScript error on ...doc.data() that says: Spread types may only be created from object types. ts(2698)但是在我下面的代码中, ...doc.data()上有一个 TypeScript 错误,上面写着: Spread types may only be created from object types. ts(2698) Spread types may only be created from object types. ts(2698)

So if data() returns an object, why is TypeScript complaining that it is not an object?因此,如果data()返回 object,为什么 TypeScript 抱怨它不是 object?

const unsubscribe = onSnapshot(
    collectionOrdered,
    (snapshot) => {
      snapshot.docs.forEach((doc) => {
        documents.push({ ...doc.data(), id: doc.id });
      });
      error.value = null;
      console.log(documents);
    },
    (err) => {
      console.log(err.message);
      documents.splice(0);
      error.value = err.message;
    }
  );

I had trouble finding it, but it looks like the doc inside snapshot needed to by typed as doc: DocumentData .我很难找到它,但看起来snapshot中的文档需要键入为doc doc: DocumentData

Full code example:完整代码示例:

const unsubscribe = onSnapshot(
    collectionOrdered,
    (snapshot) => {
      snapshot.docs.forEach((doc: DocumentData) => {
        documents.push({ ...doc.data(), id: doc.id });
      });
      error.value = null;
      console.log(documents);
    },
    (err) => {
      console.log(err.message);
      documents.splice(0); //Clears reactive array
      error.value = err.message;
    }
  );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM