Susant Patel
Susant Patel

Reputation: 55

Typescript error coming after using the spread operator on a state value

I don't know if the interface syntax is wrong code editor is happy though

interface innerQuiz1 {
  question: string;
  sectionId: number;
  attachmentId: number;
  options: string[];
  answers: string[];
}

interface innerQuiz {
  attempts: string;
  passing: string;
  quiz: innerQuiz1[];
  quizTitle: string;
}

interface courseQuiz {
  quiz: innerQuiz[];
  passing: number;
  attempts: number;
  quizTitle: string;
}

structure of the quiz is like thisconsole outpput const [courseQuiz, setCourseQuiz] = useState<courseQuiz>();

  const onQuizFormSubmit = (e) => {
    console.log("from", e);
    setCourseQuiz({
      ...e,
      quiz: e.quiz.map((item, i) => ({
        sectionId: i,
        attachmentId: null,
        question: item.question,
        options: item.answer.map((item) => item.option),
        answers: item.answer
          .filter((item) => item.checked === true)
          .map((item) => item.option),
      })),
    });
  };

This function is updating the state without any error

  const courseQuizCheck = () => {
    console.log("From course quiz check", courseQuiz);
    if (courseQuiz) return courseQuiz;
    else {
      return {
        quiz: [],
        passing: null,
        attempts: null,
        quizTitle: null,
      };
    }
  };

Again inside a function, I am trying to spread the course quiz like this

  const getCourseFromForm = () => {
    console.log("1.from getCourseFromForm", courseQuiz);
    console.log(
      "2.from getCourseFromForm after running the coursequizCheck function",
      courseQuizCheck()
    );

    console.log("4.coursequiz is spreded", ...courseQuiz);
    console.log(
      "3.from getCourseFromForm after spreading the coursequizCheckfunction",
      ...courseQuizCheck()
    );
    }

Typescript is complaining about ...courseQuiz inside 3rd console log and the error is

const courseQuiz: courseQuiz | undefined Type 'courseQuiz | undefined' is not an array type.ts(2461)

Typescript is complaining about ...courseQuizCheck() inside 4th console log and the error is

**

const courseQuizCheck: () => courseQuiz | {
    quiz: never[];
    passing: null;
    attempts: null;
    quizTitle: null;
}

Type 'courseQuiz | { quiz: never[]; passing: null; attempts: null; quizTitle: null; }' is not an array type.ts(2461) ** The console is also showing an error and the error is ** TypeError: courseQuiz is not iterable **

Upvotes: 0

Views: 439

Answers (1)

l -_- l
l -_- l

Reputation: 677

You're trying to spread the variable courseQuiz of interface CourseQuiz which looks like this :

interface courseQuiz {
  quiz: innerQuiz[];
  passing: number;
  attempts: number;
  quizTitle: string;
}

You cannot spread objects inside the console log function, only arrays.

Upvotes: 1

Related Questions