gpt4 book ai didi

typescript - rootReducer = combineReducer 使用 typescript 生成类型 'Never'

转载 作者:行者123 更新时间:2023-12-04 16:26:39 27 4
gpt4 key购买 nike

组合我的 reducer 时,类型将根 reducer 设置为 Reducer1: never, Reducer2: never
例子:

const rootReducer = combineReducers({
stories: storyReducer,
archivedStories: archiveReducer,
});

export type RootState = ReturnType<typeof rootReducer>;
storyReducer (IStory[], StoryActionTypes)
archiveReducer (number[], ArchiveActionTypes)
类型反而出现了,
故事:从不;
存档故事:从不
我遵循了另一个堆栈溢出建议并尝试指定类型。
const rootReducer: Reducer<CombinedState<{stories: IStory[]; archivedStories: number[];}>, StoryActionTypes | ArchiveActionTypes> = combineReducers({
stories: storyReducer,
archivedStories: archiveReducer,
});
但它仍然试图将它们映射到 Never
输入 'Reducer , FetchStoriesAction | AddStoriesAction | ArchiveStoryAction>' 不可分配到类型 'Reducer<{ stories: IStory[];存档故事:数字[]; }, FetchStoriesAction | AddStoriesAction | ArchiveStoryAction>'。
参数“state”和“prevState”的类型不兼容。
输入'{故事:IStory[];存档故事:数字[]; }' 不可分配给类型 'CombinedState<{ stories: never;存档故事:从不; }>'。
输入'{故事:IStory[];存档故事:数字[]; }' 不能分配给类型 '{ stories: never;存档故事:从不; }'。
属性(property)“故事”的类型是不兼容的。
类型 'IStory[]' 不可分配给类型 'never'.ts(2322)
这里有什么问题?或者如何正确指定类型?我的目标是在 IStory[] 负载上使用 .filter。
这些是 reducer :
故事 reducer
const INITIAL_STATE: IStory[] = []

const applyAddStories = (state: IStory[], action: StoryActionTypes) => action.payload;

export const storyReducer = (
state = INITIAL_STATE,
action: StoryActionTypes
) => {
switch (action.type) {
case STORIES_ADD : {
return applyAddStories(state, action)
}
default:
return state;
}
};
归档 reducer
const INITIAL_STATE: number[] = []

const applyArchiveStory = (state: number[], action: ArchiveActionTypes) => [
...state,
action.payload,
];

export const archiveReducer = (
state = INITIAL_STATE,
action: ArchiveActionTypes

) => {
switch (action.type) {
case STORY_ARCHIVE: {
return applyArchiveStory(state, action);
}
default:
return state;
}
};

export default archiveReducer;

最佳答案

我建议强制执行 reducer 的返回类型。这是我喜欢做的事情,因为它有助于对 reducer 实现进行类型检查:

//                                                           here
// v
function storyReducer(state: IStory[], action: StoryActionTypes): IStory[] {
// ...
}
您不需要显式键入reducer,它只适用于您的原始代码:
const rootReducer = combineReducers({
stories: storyReducer,
archivedStories: archiveReducer,
});

export type RootState = ReturnType<typeof rootReducer>;
这是一个演示结果的操场: link

关于typescript - rootReducer = combineReducer 使用 typescript 生成类型 'Never',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62706721/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com