Skip to content

Instantly share code, notes, and snippets.

@vincentbel
Last active January 21, 2018 01:40
Show Gist options
  • Select an option

  • Save vincentbel/1478680787ff9cd3db2f98cdc413e06a to your computer and use it in GitHub Desktop.

Select an option

Save vincentbel/1478680787ff9cd3db2f98cdc413e06a to your computer and use it in GitHub Desktop.
redux + typescript
// User module
const enum UserActionTypes {
UserRequest = 'user/user-request',
UserSuccess = 'user/user-success',
UserFailure = 'user/user-failure',
RoleRequest = 'user/role-request',
RoleSuccess = 'user/role-success',
RoleFaliure = 'user/role-failure',
}
interface UserRequestAction {
type: UserActionTypes.UserRequest,
userId: string,
}
interface UserSuccessAction {
type: UserActionTypes.UserSuccess,
userId: string,
response: any,
}
interface UserFailureAction {
type: UserActionTypes.UserFailure,
userId: string,
error: Error,
}
function startLoadUser(userId: string): UserRequestAction {
return {
type: UserActionTypes.UserRequest,
userId,
}
}
function loadUserSuccess(userId: string, response: any): UserSuccessAction {
return {
type: UserActionTypes.UserSuccess,
userId,
response,
}
}
function loadUserFailed(userId: string, error: Error): UserFailureAction {
return {
type: UserActionTypes.UserFailure,
userId,
error,
}
}
// We can use this if typescript support getting the type of a function
// https://github.com/Microsoft/TypeScript/issues/6606
//
// type UserActions =
// | typeof startLoadUser(string),
// | typeof loadUserSuccess(string, any),
// | typeof loadUserFailed(string, Error),
type UserActions =
| UserRequestAction
| UserSuccessAction
| UserFailureAction
// Food module
const enum FoodActionTypes {
EatApple = 'food/eat-apple',
EatBanana = 'food/eat-banana',
}
interface EatAppleAction {
type: FoodActionTypes.EatApple,
foodId: string,
}
interface EatBananaAction {
type: FoodActionTypes.EatBanana,
foodId: string,
}
type FoodActions =
| EatAppleAction
| EatBananaAction
// Main
type Actions =
| UserActions
| FoodActions
function myReducer(state: number, action: Actions): number {
switch (action.type) {
case UserActionTypes.UserRequest:
case UserActionTypes.UserSuccess:
case UserActionTypes.UserFailure:
return state + 1
case FoodActionTypes.EatApple:
case FoodActionTypes.EatBanana:
return state + 2
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment