Redux Toolkit中createSlice的reducer出现Argument of type 'any' is not assignable to parameter of type 'never'错误的问题咨询
解决Redux Toolkit中TypeScript的
never类型错误 嘿,这个问题我之前也踩过坑,核心原因其实很简单:TypeScript没法自动推断空数组的具体元素类型,所以你的initialState: []被默认推断成了never[]——也就是永远不能包含任何元素的数组,自然你往里面push任何内容都会报类型不匹配的错误。
而且你尝试把getData声明成any[]是个小误区:getData明明是一个包含type和data的对象,不是数组,这个类型声明完全不对,当然解决不了问题啦。
下面给你几个靠谱的解决方案:
方案1:给initialState指定明确的类型(最推荐)
先定义你要存入数组的元素结构,再给初始状态指定对应类型:
// 先定义数组元素的类型,尽量别用any,替换成你实际的data类型 interface TestItem { type: string; data: YourDataType; // 这里换成你真实的data类型,比如string/number/自定义接口 } const testSlice = createSlice({ name: "test", // 明确指定initialState是TestItem类型的数组 initialState: [] as TestItem[], reducers: { callApi: (state, action) => { const getData = { type: "test/getData", data: action.payload }; state.push(getData); } } });
方案2:用createSlice的泛型参数指定类型
如果觉得上面的写法不够直观,也可以直接给createSlice传入泛型参数,明确state和reducers的类型:
import { createSlice, PayloadAction } from '@reduxjs/toolkit'; interface TestItem { type: string; data: YourDataType; } const testSlice = createSlice<TestItem[], { callApi: (state: TestItem[], action: PayloadAction<YourDataType>) => void }>({ name: "test", initialState: [], reducers: { callApi: (state, action) => { const getData = { type: "test/getData", data: action.payload }; state.push(getData); } } });
小提醒
尽量避免用any类型,把YourDataType换成你实际业务中action.payload的具体类型,这样TypeScript才能帮你提前发现类型错误,这也是用TS的意义呀~
内容的提问来源于stack exchange,提问作者Johan
相关产品推荐
相关产品推荐

