我使用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的内容,但都没有成功。
1条答案
按热度按时间50few1ms1#
Typescript显示此错误的原因是因为您初始化了一个空数组,但没有提供其类型,这将导致数组默认为
any[]
类型。Typescript只能在以下情况下推断类型:在您的例子中,由于您知道数据的形状,因此可以为数组的内容创建一个类型,并在定义变量时注解该类型。有关详细信息,请参阅Typescripts type inference文档。