3

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.

Rashomon
  • 5,962
  • 4
  • 29
  • 67

1 Answers1

12
    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.

phry
  • 35,762
  • 5
  • 67
  • 81
  • Thanks man, exactly what I was looking for :) Do you mind explaining why the error was there in the first place, and why this fixes it? – Michael Vigato Jun 05 '22 at 07:57
  • 1
    @MichaelVigato Because the return value of `prepare` and the `action` argument of `reducer` need to have the same type. The return value of `prepare` can be inferred by TypeScript (all types are known here), but the input value to `reducer` cannot be inferred - you'll have to specify that manually or it will fall back to some generic fallback that will cause you errors. – phry Jun 05 '22 at 08:06
  • 1
    For what it's worth, there is also a [TypeScript example in the `createSlice` api documentation](https://redux-toolkit.js.org/api/createSlice#customizing-generated-action-creators) showcasing how to type this. – phry Jun 05 '22 at 08:07