skip to Main Content

I am using Next.js/React + Firebase as the backend for a To Do List (containing name, time task will take and due date fields). I am trying to get the items from the Firebase collection and push it to setData so I can display them in a table, but am getting the following error:

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

Below is my code:

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();
          };
        }, []);

I have tried changing the type of l and changing what’s being pushed to l but neither has worked.

2

Answers


  1. The reason why Typescript is showing you this error is because you have initialized an empty array without providing its type, this will result in the array being of type any[] by default. Typescript is only able to infer the type in following cases:

    // annotate the type
    const myArray1: Array<{ id: string }> = [];
    
    // infer type from data
    const myArray2 = [{ id: "22" }];
    

    In your case, since you know the shape of the data you can create a type for the content of your array, and annotate the type upon definition of your variable. For more details check out Typescripts type inference documentation.

    Login or Signup to reply.
  2. Typescript has a powerful type inference system that can automatically infer the types of generic type parameters based on the values passed to them. This helps your code to be more concise and readable because it lessens the amount of explicit type annotation you need to write. But this doesn’t always work because there are some locations where the type of a generic variable is indeterminable.

    To solve this you can manually infer the type.

    const l: Array<{id: string}> = [];
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search