You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 00:19:08