Last active
January 10, 2025 19:22
-
-
Save milankorsos/ffb9d32755db0304545f92b11f0e4beb to your computer and use it in GitHub Desktop.
Correct TypeScript typing example for Redux Thunk actions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {Action, ActionCreator, Dispatch} from 'redux'; | |
import {ThunkAction} from 'redux-thunk'; | |
// Redux action | |
const reduxAction: ActionCreator<Action> = (text: string) => { | |
return { | |
type: SET_TEXT, | |
text | |
}; | |
}; | |
// Redux-Thunk action | |
const thunkAction: ActionCreator<ThunkAction<Action, IState, void>> = ( | |
text: string | |
) => { | |
return (dispatch: Dispatch<IState>): Action => { | |
return dispatch({ | |
type: SET_TEXT, | |
text | |
}); | |
}; | |
}; | |
// Async Redux-Thunk action | |
const asyncThinkAction: ActionCreator< | |
ThunkAction<Promise<Action>, IState, void> | |
> = () => { | |
return async (dispatch: Dispatch<IState>): Promise<Action> => { | |
try { | |
const text = await Api.call(); | |
return dispatch({ | |
type: SET_TEXT, | |
text | |
}); | |
} catch (e) {} | |
}; | |
}; |
Please hellp me )))
export type ThunkResult2<R> = ThunkAction<R, AppStateType, null, Action>
export type ThunkDispatch2 = ThunkDispatch<AppStateType, null, Action>
export const login = (auth: any): ThunkResult2<Promise<{a: boolean, b: string}>> => async (dispatch: ThunkDispatch2) => {
const res = await AuthApi.authentication(auth);
const r = dispatch(AuthActions.login(new Auth({ ...res })));
return {
a: true,
b: '123'
} // this very well work
}
// but
......
onSubmit={ async (values) => {
const res = await dispatch(login(values))
console.log(res.a) // this problem
}}
TS2339: Property 'a' does not exist on type 'ThunkAction { a: boolean; b: string; }>, CombinedState{ auth: never; }>, null, Action >'
I still can't locate IStoreState
Maybe this is right place to use "any" when i must make type for thunk action in my props.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks @milankorsos!