打字稿:'{translationSentences:never []; }'不可分配给'never'类型的参数

时间:2020-09-29 14:45:39

标签: reactjs typescript react-hooks

我知道在stackoverflow上也曾提出过类似的问题,我一直在阅读它们并尝试实现他们的解决方案。但是,经过一个多小时的尝试来改变一百万种不同的事物之后,我距离了解这个问题或解决问题的方式越来越近了。

我正在尝试将类型添加到我的reducer中,但此错误却无济于事:

enter image description here

InitialState

export const initialState = {
  activeStep: 0,
  notification: {
    format: undefined,
    message: "",
  },
  lesson: {
    title: "",
    language: { language: "", code: "" },
    topics: [],
    format: "",
    url: "",
    file: EMPTY_FILE,
    totalPoints: 0,
    totalWords: 0,
  },
  newWords: [],
  initialTranscript: [],
  modifiedTranscript: [],
  transcriptSentences: [],
  translatedSentences: [],
};

减速器

export const reducer = (state: InitialState = initialState, action: Action) => {
  switch (action.type) {
    ...

    case ActionTypes.SET_SENTENCE_TRANSLATIONS:
      return {
        ...state,
        translatedSentences: action.payload,
      };
    case ActionTypes.SET_SENTENCE_TRANSLATION:
      const { sentence, id } = action.payload;
      const translatedSentencesClone = state.translatedSentences.slice();
      translatedSentencesClone[id] = sentence;
      return {
        ...state,
        translatedSentences: translatedSentencesClone,
      };

    ...

  }
}

类型

export type TranslatedSentence = {
  id: number;
  source: string;
  translation: string;
  approved?: boolean;
};


// for the initial batch of all translations
interface SET_SENTENCE_TRANSLATIONS {
  type: ActionTypes.SET_SENTENCE_TRANSLATIONS;
  payload: TranslatedSentence[];
}

// for updating one translations
interface SET_SENTENCE_TRANSLATION {
  type: ActionTypes.SET_SENTENCE_TRANSLATION;
  payload: { sentence: TranslatedSentence; id: number };
}

希望那是足够的材料,如果没有让我知道的话。我很沮丧,这时感觉很迷茫。

1 个答案:

答案 0 :(得分:1)

我本来要发表另一条评论,但是TS Playground link太长了,无法包含。

您想要的是减速器取var x = document.getElementById("results_table"); var y = x.querySelector("tr"); y.remove(); State并返回与输入相同类型的Action

您的State变量应满足您的initialState接口,但其他任何有效状态也应满足。如果使用State创建typeof initialState接口,则会出错,因为这表明属性State只能是空数组,也就是translatedSentances。我还没有看到类型never[]的定义,但是奇怪的是,您使用InitialState来表示化石的状态,而不仅仅是使用InitialState,这使我想到请注意,State类型的内容可能不是您想要的。

在您提供的代码段中,您仅在编辑InitialState属性,因此您的translatedSentences类型可以很简单:

State

而您的interface State { translatedSentences: TranslatedSentence[]; } 类型是联合:

Action

您的减速器应具有签名:

type Action = SET_SENTENCE_TRANSLATION | SET_SENTENCE_TRANSLATIONS;

使用const reducer = (state: State, action: Action): State 不会有任何问题-希望如此!