Action Creator with TypeScript Enum
Implement an action creator using TypeScript enum to enforce string type actions and illustrate best type safety practices.
enum ActionType {
FETCH_USER = 'FETCH_USER',
FETCH_USER_SUCCESS = 'FETCH_USER_SUCCESS',
FETCH_USER_FAILURE = 'FETCH_USER_FAILURE'
}
// Define an interface for the Action with a 'type' that accepts 'ActionType'
interface FetchUserAction {
type: ActionType.FETCH_USER;
}
interface FetchUserSuccessAction {
type: ActionType.FETCH_USER_SUCCESS;
payload: { user: any }; // Replace 'any' with a more specific type for user data
}
interface FetchUserFailureAction {
type: ActionType.FETCH_USER_FAILURE;
error: string;
}
// Union type for User Actions
type UserActions = FetchUserAction | FetchUserSuccessAction | FetchUserFailureAction;
// Action Creator for fetching user
export function fetchUser(): FetchUserAction {
return { type: ActionType.FETCH_USER };
}
// Action Creator for a successful user fetch
export function fetchUserSuccess(user: any): FetchUserSuccessAction { // Replace 'any' with a specific type
return {
type: ActionType.FETCH_USER_SUCCESS,
payload: { user }
};
}
// Action Creator for a failed user fetch
export function fetchUserFailure(error: string): FetchUserFailureAction {
return {
type: ActionType.FETCH_USER_FAILURE,
error
};
}
This code defines a TypeScript enum 'ActionType' that contains actions for fetching a user. Corresponding interfaces define the shape of actions for different cases: fetch start, success, and failure. Union type 'UserActions' is created to represent all possible user actions. Functions 'fetchUser', 'fetchUserSuccess', and 'fetchUserFailure' are action creators that return actions with types specified by the 'ActionType' enum, ensuring the objects conform to the structure dictated by their respective interfaces.