reactjs React +Firestore中的Typescript错误:为什么我会得到“变量'l'在某些无法确定其类型的位置隐式地具有类型'any[]',ts”

1cosmwyk  于 12个月前  发布在  React
关注(0)|答案(1)|浏览(1243)

我使用Next.js/React + Firebase作为待办事项列表的后端(包含名称、任务时间和截止日期字段)。我试图从Firebase集合中获取项目,并将其推送到setData,以便在表中显示它们,但收到以下错误:

Variable 'l' implicitly has type 'any[]' in some locations where its type cannot be determined.ts(7034)

下面是我的代码:

import { useEffect, useState } from "react"
import { db } from '../services/firebase.config'
import { collection, getDocs, onSnapshot, Firestore, QueryDocumentSnapshot, DocumentData } from 'firebase/firestore'

const ToDoData = () => {
    const [data, setData] = useState();

    useEffect(()=> {
        const unsub = onSnapshot(
            collection(db, "taskList"),
            (snapShot) => {
              const l =[]; // I AM GETTING THE ERROR HERE
              snapShot.forEach((doc) => {
                l.push({id: doc.id, ...doc.data()});
              });
              setData(l);
            },
            (error) => {
              console.log(error);
            }
          );
      
          return () => {
            unsub();
          };
        }, []);

我试过改变l的类型,改变被推到l的内容,但都没有成功。

50few1ms

50few1ms1#

Typescript显示此错误的原因是因为您初始化了一个空数组,但没有提供其类型,这将导致数组默认为any[]类型。Typescript只能在以下情况下推断类型:

// annotate the type
const myArray1: Array<{ id: string }> = [];

// infer type from data
const myArray2 = [{ id: "22" }];

在您的例子中,由于您知道数据的形状,因此可以为数组的内容创建一个类型,并在定义变量时注解该类型。有关详细信息,请参阅Typescripts type inference文档。

相关问题