![](/img/trans.png)
[英]React TypeScript: Argument is not assignable to parameter of type 'never'
[英]Typescript: '{ translatedSentences: never[]; }' is not assignable to parameter of type 'never'
我知道在 stackoverflow 上也有人问过类似的问题,我一直在阅读它们并尝试实施他们的解决方案。 但是,在尝试改变一百万种不同的事情一个多小时后,我并没有更接近于理解这个问题或如何解决它。
我正在尝试向我的减速器添加类型,但此错误无济于事:
初始状态
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 };
}
希望这是足够的材料,如果没有让我知道。 在这一点上,我很难过,感觉很失落。
我打算再发表评论,但TS Playground 链接太长,无法包含。
你需要的是你的减速采取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
使用useReducer
应该不会有任何问题——我希望!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.