Skip to content

Instantly share code, notes, and snippets.

@RyanCCollins
Last active January 5, 2017 05:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RyanCCollins/8dcd81dbd8fa96bccff7f6e712c7d5a7 to your computer and use it in GitHub Desktop.
Save RyanCCollins/8dcd81dbd8fa96bccff7f6e712c7d5a7 to your computer and use it in GitHub Desktop.
TypeScript Union Types
type FeedbackAction = 'FEEDBACK_SUBMISSION_INITIATION' | 'FEEDBACK_SUBMISSION_MESSAGE' | 'FEEDBACK_SUBMISSION_ERROR'; // etc. etc.
interface IAction<P> {
type: FeedbackAction;
payload: P;
};
interface IFeedbackState {
error: Error;
message: string;
isSubmitting: boolean;
};
// we could even get fancy here and define our own Maybe type
// instead of using those pesky nulls.
export const initialState: IAppState = {
error = null,
message = null,
isSubmitting = false,
};
const feedbackReducer = (state: IFeedbackState = initialState, action: IAction<any>): IFeedbackState => {
switch (action.type) {
// oops we forgot to declare this type.
// Not to worry, the compiler has our back!
// The compiler warns us that FEEDBACK_CLEAR_ALERTS is not a valid FeedbackAction.
case 'FEEDBACK_CLEAR_ALERTS':
return {
...state,
error: null,
message: null,
};
case 'FEEDBACK_SUBMISSION_INITIATION':
return {
...state,
isSubmitting: true,
};
case 'FEEDBACK_SUBMISSION_ERROR':
return {
...state,
isSubmitting: false,
error: action.payload.error,
};
case 'FEEDBACK_SUBMISSION_MESSAGE':
return {
...state,
isSubmitting: false,
message: action.payload.message,
};
default:
return state;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment