Can’t use useReducer Hook with in a Typescript Next Js project

Issue

This Content is from Stack Overflow. Question asked by Gourav Kumar

I am very new to Typescript and I am here trying to use the useReducer hook with Typescript.

This is my code:

import { useReducer, useContext, createContext } from "react"
import type { ReactNode } from "react"

const defaultState = { count: 0}

const CounterContext = createContext(undefined)

export type Action = 'increment' | 'decrement'
export type State = typeof defaultState
export type Dispatch = (action: Action) => void

const counterReducer = (state: State, action: Action) => {
    switch(action) {
        case 'increment': return state.count = state.count + 1
        case 'decrement': return state.count = state.count - 1
        default: state
    }
}

const CounterProvider = ({children}: {children: ReactNode}) => {
    
    const [state, dispatch] = useReducer(counterReducer,defaultState)
...
}

I am getting an error in this line:

const [state, dispatch] = useReducer(counterReducer,defaultState)

Error is:

    No overload matches this call.
  Overload 1 of 5, '(reducer: ReducerWithoutAction<any>, initializerArg: any, initializer?: undefined): [any, DispatchWithoutAction]', gave the following error.
    Argument of type '(state: State, action: Action) => number | undefined' is not assignable to parameter of type 'ReducerWithoutAction<any>'.
  Overload 2 of 5, '(reducer: (state: { count: number; }, action: Action) => number | undefined, initialState: never, initializer?: undefined): [never, Dispatch<Action>]', gave the following error.
    Argument of type '{ count: number; }' is not assignable to parameter of type 'never'.

Can you guys please tell me what I am doing wrong? Thanks.



Solution

This question is not yet answered, be the first one who answer using the comment. Later the confirmed answer will be published as the solution.

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?