简体   繁体   中英

React Redux dispatch function: Expected 0 arguments, but got 1 TS2554

The code in question looks like this:

// Actions (in a separate file)
export const contextFilesAddAction = (payload: IContextFile) => ({
  type: CONTEXT_FILES_ADD,
  payload,
})

...

const App = () => {
  const [contextFiles, dispatch] = React.useReducer(contextFilesReducer, [])
  const contextFilesAdd = (payload: IContextFile) =>
    dispatch(contextFilesAddAction(payload))
  const contextFilesRemove = (id: string) =>
    dispatch(contextFilesRemoveAction(id))
  const contextFilesClear = () => dispatch(contextFilesClearAction())
  const contextFilesGet = (id: string) => {
    const ctxFile = contextFiles.find(f => f.id === id)
    if (typeof ctxFile === 'undefined') {
      throw Error('No context file found')
    }
    return ctxFile
  }
...

On each of the dispatch lines I receive the error stated in the title.

When I go to the definition of these functions, I can see that sitting directly next to them is an overload for a function that accepts an argument, as it is being used here.

Is there a reason why it chooses the overload that doesn't accept an argument?

You need to add the type for useReducer.

I got same error while using createAction from @reduxjs/toolkit

This was my code

export const setClientId = createAction('setClientId');

setClientId('abc') // would throw error, expected 0 
//arguments but got 1, realized that I also need to provide type of argument

//Solution : add <string> after createAction
export const setClientId = createAction<string>('setClientId');

setClientId('abc') // works well.



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