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

Redux Toolkit+TypeScript场景下PayloadAction的正确类型如何定义?

问题原因

你当前的错误完全来自PayloadAction的泛型参数填写错误,和initialState的定义无关。
你写的PayloadAction<"people"[]>中的"people"是TS字符串字面量类型,相当于你声明这个action的payload是由字符串"people"组成的数组,和people字段要存储的对象结构完全不匹配,所以TS会抛出缺少name、age、url属性的错误。


解决方案

首先可以先抽离单个受邀者的类型,避免重复编写类型定义,也方便后续复用:

// 定义单个受邀者的类型,对应people数组的每个元素结构
interface Invitee {
  name: string;
  age: number;
  url: string;
  note?: string;
}

// 复用上面的Invitee定义state类型
interface InviteeState {
  people: Invitee[];
}

const initialState: InviteeState = {
  people: [], 
}

之后根据你addInvitee的使用场景,选择对应的类型定义即可:

场景1:每次添加单个受邀人

action的payload是单个Invitee对象,reducer定义如下:

export const inviteesSlice = createSlice({
  name: "invitees",
  initialState,
  reducers: {
    addInvitee: (state, action: PayloadAction<Invitee>) => {
        state.people.push(action.payload)
    }
  }
})
// 调用方式示例:dispatch(addInvitee({name: "张三", age: 25, url: "xxx"}))

场景2:每次添加多个受邀人

action的payload是Invitee数组,需要解构后再push到state里:

export const inviteesSlice = createSlice({
  name: "invitees",
  initialState,
  reducers: {
    addInvitee: (state, action: PayloadAction<Invitee[]>) => {
        state.people.push(...action.payload)
    }
  }
})
// 调用方式示例:dispatch(addInvitee([{name: "张三", age: 25, url: "xxx"}, {name: "李四", age: 22, url: "yyy"}]))

内容的提问来源于stack exchange,提问作者reknirt

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 21:36:03