Search code examples
reactjstypescriptreact-typescript

React - Type '(studentIds: Student[])' is missing the following properties from type 'Stduent[]' length, pop, push, concat, and 26 more. [2740]


I'm getting an error that says:

Type '(studentIds: string[]) => Promise<void>' is missing the following properties from type 'string[]': 
    pop, push, concat, join, and 28 more.ts(2740)
StudentModal.tsx(143, 27): The expected type comes from property 'students' which is declared here on 
    type 'IntrinsicAttributes & Props & { children?: ReactNode; }'

My component has props defined as:

interface Props {
  isOpen: boolean;
  students: Array<Student['id']>;
  onStudents: () => void;
  onClose: () => void;
}

It is called as:

<StudentModal
   isOpen={isOpenStudentsModal}
   students={getStudents}
   onStudents={studentCallback}
   onClose={studentToggle}    
 />

whereas getStudents is defined as:

export const getStudents = async(studentIds: Array<Student['id']>) : Promise<void> =>
{
 // service call to get student ids
};

As far as I can see, parameter list on getStudents matches the one on the Props interface. What am I doing wrong here?


Solution

  • Your interface defined students as

      students: Array<Student['id']>;
    

    but when you render the component, you are passing in the function of getStudents

    students={getStudents}
    

    so the type you passed into the component is (studentIds: string[]) => Promise<void> and not string[].

    What the error is saying is that the prop passed in do not have array methods like pop/push.

    Since getStudents is a async function, you probably need to store the result in the state, then pass that state into the Model.

    For example,

    function Main() {
      const [studentIds, setStudentIds] = useState<string[]>([]);
    
      useEffect(() => {
        getStudents().then(studentIds => setStudentIds(studentIds))
      }, []);
    
      return (
        <StudentModal
          students={studentIds}
          ...
        />
      );
    }