Skip to content

Instantly share code, notes, and snippets.

@smashingpat
Created October 23, 2018 11:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smashingpat/2cafada1e7b55b6eae58eb8fffeb5678 to your computer and use it in GitHub Desktop.
Save smashingpat/2cafada1e7b55b6eae58eb8fffeb5678 to your computer and use it in GitHub Desktop.
Typescript Redux actionTypes
import { Dispatch } from 'redux';
type StoreState = any; // preferable this should be the real Type of the store
/** Default action with just the type */
interface Action<T extends string> {
readonly type: T;
}
/** Action extended with a payload that could be any value, used for the reducer */
interface ActionWithPayload<T extends string, P> extends Action<T> {
payload: P;
}
/** Factory for an action with the correct ReturnType so Typescript can process it */
export function createAction<T extends string>(type: T): Action<T>;
export function createAction<T extends string, P>(type: T, payload: P): ActionWithPayload<T, P>;
export function createAction<T extends string, P>(type: T, payload?: P) {
return payload === undefined
? { type }
: { type, payload };
}
interface ThunkAction<R, S> {
(dispatch: Dispatch<Action<any>>, getState: () => S): R;
}
export function createThunkAction<R, S = StoreState>(thunkAction: ThunkAction<R, S>) {
// set the Type to unknown. This function is passed through
// `redux-thunk` and so the return value should be the type
// Due the original Dispatch method not having the correct
// ReturnType this is an alternative way to get it
const processedThunkAction = thunkAction as unknown;
return processedThunkAction as R;
}
/*
* createAction will return an object with 'type' and 'payload',
* the payload is only set in the type when a second argument is set.
*
* Additionally you can get the below ActionType by using `type SetNameAction = ReturnType<typeof setName>`
*/
//
const setName = (name: string) => createAction('SET_NAME', name);
/*
* A thunkAction normally returns a function that might return a value. But
* if this is used in the store.dispatch the ReturnType is the thunkAction.
* `createThunkAction` changes the ReturnType to be the ReturnType of the
* ThunkAction as expected
*/
const fetchName = (name: string) => createThunkAction((dispatch, getState) => {
const name = getNameFromSomewhere();
dispatch(setName(name));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment