Last active
January 5, 2017 05:36
-
-
Save RyanCCollins/8dcd81dbd8fa96bccff7f6e712c7d5a7 to your computer and use it in GitHub Desktop.
TypeScript Union Types
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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