Skip to content

Instantly share code, notes, and snippets.

@zzdjk6
Last active February 13, 2020 09:27
Show Gist options
  • Save zzdjk6/ce300dd9590eb5f13cefd391ff5412e7 to your computer and use it in GitHub Desktop.
Save zzdjk6/ce300dd9590eb5f13cefd391ff5412e7 to your computer and use it in GitHub Desktop.
// Use type guards
const reducer = (state: State = initState, action: Action<any>): State => {
// isSuccessAction is a type guard
if (fetchDataRoutine.isSuccessAction(action)) {
// action is typed as Action<DataType>, so payload is DataType
const payload = action.payload;
// ...
}
// isFailureAction is a type guard
if (fetchDataRoutine.isFailureAction(action)) {
// action is typed as Action<Error>, so error is Error
const error = action.payload;
// ...
}
};
// Use getter functions directly
const reducer = (state: State = initState, action: Action<any>): State => {
switch (action.type) {
case fetchDataRoutine.SUCCESS: {
// payload is typed as Action<DataType>
const payload = fetchDataRoutine.getSuccessPayload(action);
// ...
break;
}
case fetchDataRoutine.FAILURE: {
// error is typed as Error
const error = fetchDataRoutine.getFailurePayload(action);
// ...
break;
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment