前提
TypeScript、Reactを使ってUseReducerを使おうとしています。
MERNでログイン機能のフロント側を作っているのですがUseReducerの所でエラーが発生しました。
実現したいこと
TypeScriptでUseReducerを使う
エラーメッセージ この呼び出しに一致するオーバーロードはありません。 5 中 1 のオーバーロード, '(reducer: ReducerWithoutAction<any>, initializerArg: any, initializer?: undefined): [any, DispatchWithoutAction]' により、次のエラーが発生しました。 型 '(state: State, action: ACTIONTYPE) => State | { user: { user: string | null; }; }' の引数を型 'ReducerWithoutAction<any>' のパラメーターに割り当てることはできません。 5 中 2 のオーバーロード, '(reducer: (state: State, action: ACTIONTYPE) => State | { user: { user: string | null; }; }, initialState: never, initializer?: undefined): [never, Dispatch<...>]' により、次のエラーが発生しました。 型 '{ user: null; }' の引数を型 'never' のパラメーターに割り当てることはできません。ts(2769)
該当のソースコード
TypeScript
1ソースコード 2import React, { createContext, useReducer } from "react"; 3 4type authProviderProps = { 5 children: JSX.Element | JSX.Element[]; 6}; 7 8type LoginAction = { 9 type: "LOGIN"; 10 payload: { user: string | null }; 11}; 12type LogoutAction = { 13 type: "LOGOUT"; 14}; 15 16type ACTIONTYPE = LoginAction | LogoutAction; 17 18type createContextProps = { 19 state: string; 20 dispatch: React.Dispatch<ACTIONTYPE>; 21}; 22 23type Iuser = { 24 _id: string; 25 email: string; 26 password: string; 27} | null; 28 29type State = { 30 user: Iuser; 31}; 32 33export const authContext = createContext({} as createContextProps); 34 35export const authReducer = (state: State, action: ACTIONTYPE) => { 36 switch (action.type) { 37 case "LOGIN": 38 return { user: action.payload }; 39 case "LOGOUT": 40 return { user: null }; 41 default: 42 return state; 43 } 44}; 45 46const initialState: State = { 47 user: null, 48}; 49 50export const AuthContextProvider = ({ children }: authProviderProps) => { 51 const [state, dispatch] = useReducer(authReducer, initialState); //<-ここでエラー 52 53 console.log("AuthContext state:", state); 54 55 return ( 56 <authContext.Provider value={{ ...state, dispatch }}> 57 {children} 58 </authContext.Provider> 59 ); 60}; 61
試したこと
このエラーメッセージに関して検索してみたところ、throw Errorをconsole.errorにしてしまった場合、redecerの返り値をすべて型定義しない場合に発生する、という2つを見つけました。前者の可能性は無いと思いますので恐らく後者が原因ではないかと考えています。
補足情報(FW/ツールのバージョンなど)
react 17.0.2
typescript 4.6.2
state の型が合ってません。
type State は { user: Iuser } なのに、authReducer が LOGIN の際に返すものは { user: { user: string | null } } になってます。
(あと、type Iuser は | null を含まないほうが扱いやすいのでは…。)