繁体   English   中英

在状态值上使用扩展运算符后出现打字稿错误

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

我不知道界面语法是否错误代码编辑器很高兴

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;
}

测验的结构是这样的控制台输出 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),
      })),
    });
  };

此函数正在更新状态,没有任何错误

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

再次在函数内部,我试图像这样传播课程测验

  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 在第三个控制台日志中抱怨...courseQuiz并且错误是

常量课程测验:课程测验 | 未定义类型'courseQuiz | undefined' 不是数组类型。ts(2461)

Typescript 在第 4 个控制台日志中抱怨...courseQuizCheck() ,错误是

**

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

键入“课程测验 | {测验:从不[]; 通过:空; 尝试:空; 测验标题:空; }' 不是数组类型。ts(2461) ** 控制台也显示错误,错误是 ** TypeError: courseQuiz is not iterable **

您正在尝试传播接口 CourseQuiz 的变量 courseQuiz,如下所示:

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

您不能在控制台日志函数中传播对象,只能传播数组。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM