Reduce Redux's action-creator boilerplates without library support in TypeScript

airtoxin

Ryoji Ishii

Posted on April 15, 2019

Reduce Redux's action-creator boilerplates without library support in TypeScript
// Define action-creators
export const fetchPostsRequest = () => ({
  type: "FETCH_POSTS" as const
});
export const fetchPostsSuccess = (posts: any) => ({
  type: "FETCH_POSTS_SUCCESS" as const,
  payload: { posts }
});
export const fetchPostsFailure = (error: Error) => ({
  type: "FETCH_POSTS_FAILURE" as const,
  error
});

// Define Action and ActionTypes
export type FetchPostAction = ReturnType<
  | typeof fetchPostsRequest
  | typeof fetchPostsSuccess
  | typeof fetchPostsFailure
>
export type FetchPostsActionTypes = FetchPostAction["type"];

// Let's use
const action: FetchPostAction = {
  type: "FETCH_POSTS_FAILURE"
}; // -> Property 'error' is missing
💖 💪 🙅 🚩
airtoxin
Ryoji Ishii

Posted on April 15, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related