简体   繁体   中英

How to type 'prepare' function in redux-toolkit

I am using redux-toolkit prepare function to construct the final payload value.

    addTodo: {
      reducer: (state, action) => {
        state.push(action.payload);
      },
      // ERROR: **Type '{ payload: Todo; }' is missing the following properties from type 'Omit<PayloadAction<any, string, any, any>, "type">': meta, errorts**
      prepare: (todoMessage: string): { payload: Todo } => {
        return {
          payload: { message: todoMessage, id: uuid(), completed: false }
        };
      }
    },

How can I type prepare function to remove the typescript error?

Check the error here .

    addTodo: {
      reducer: (state, action: PayloadAction<Todo>) => {
        state.push(action.payload);
      },
      prepare: (todoMessage: string) => {
        return {
          payload: { message: todoMessage, id: uuid(), completed: false }
        };
      }
    },

you just need to add a payload type on the action .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM