Typescript类型错误:{ translatedSentences: never[]; }无法赋值给never类型参数求解
解决TypeScript Reducer中的
never类型不匹配错误 看起来你遇到的问题是TypeScript无法正确推断reducer状态和action的类型,导致出现'{ translatedSentences: never[]; }' is not assignable to parameter of type 'never'的错误。我来帮你一步步排查和解决:
问题根源
这个错误通常由两个核心原因导致:
InitialState类型未明确声明:你的initialState对象里translatedSentences是空数组,TypeScript无法自动推断它的具体类型,默认将其设为never[],当你在reducer中尝试更新这个数组时,就会和期望的类型冲突。Action联合类型不完整:如果你的Action类型没有包含SET_SENTENCE_TRANSLATIONS和SET_SENTENCE_TRANSLATION这两个action接口,TypeScript会把reducer中的action推断为never,进而导致payload的类型无法识别。
解决方案
1. 明确定义InitialState类型
首先,你需要为initialState创建一个清晰的类型,把translatedSentences明确指定为TranslatedSentence[]:
import { TranslatedSentence } from './path-to-your-types'; // 先定义子类型,让整体结构更清晰 type Notification = { format: undefined | string; // 明确format的可能取值类型 message: string; }; type LessonLanguage = { language: string; code: string; }; type Lesson = { title: string; language: LessonLanguage; topics: any[]; // 如果有Topic类型,替换成Topic[]会更严谨 format: string; url: string; file: typeof EMPTY_FILE; // 替换成EMPTY_FILE的实际类型 totalPoints: number; totalWords: number; }; // 最终的InitialState类型 export type InitialState = { activeStep: number; notification: Notification; lesson: Lesson; newWords: any[]; // 替换成具体类型(如果有的话) initialTranscript: any[]; // 替换成具体类型(如果有的话) modifiedTranscript: any[]; // 替换成具体类型(如果有的话) transcriptSentences: any[]; // 替换成具体类型(如果有的话) translatedSentences: TranslatedSentence[]; // 关键:明确这里的类型 };
2. 确保Action联合类型包含所有action
接下来,把你定义的两个action接口加入到Action联合类型中,同时确认ActionTypes枚举正确定义:
// 先定义ActionTypes枚举 export enum ActionTypes { SET_SENTENCE_TRANSLATIONS = 'SET_SENTENCE_TRANSLATIONS', SET_SENTENCE_TRANSLATION = 'SET_SENTENCE_TRANSLATION', // 其他action类型... } // 你的两个action接口 interface SET_SENTENCE_TRANSLATIONS { type: ActionTypes.SET_SENTENCE_TRANSLATIONS; payload: TranslatedSentence[]; } interface SET_SENTENCE_TRANSLATION { type: ActionTypes.SET_SENTENCE_TRANSLATION; payload: { sentence: TranslatedSentence; id: number }; } // 联合所有action类型,确保reducer能识别每一种action export type Action = SET_SENTENCE_TRANSLATIONS | SET_SENTENCE_TRANSLATION | /* 其他你的action类型 */;
3. 完善Reducer的类型声明
确保你的reducer的state参数明确使用InitialState类型,同时不要忘记添加default分支:
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 }; // 其他case... default: return state; // 必须添加default分支,否则TypeScript会提示返回类型不完整 } };
额外提示
- 尽量避免使用
any类型,如果有具体的子类型(比如newWords对应的类型),一定要替换成具体类型,这样TypeScript才能更好地帮你提前发现错误。 - 确保
EMPTY_FILE有明确的类型定义,避免lesson.file的类型模糊。
这样调整后,TypeScript就能正确识别translatedSentences的类型,你遇到的never类型不匹配错误应该就会消失了。
内容的提问来源于stack exchange,提问作者kevin
相关产品推荐
相关产品推荐

