Skip to content

Instantly share code, notes, and snippets.

@isthatcentered
Last active April 11, 2019 06:44
Show Gist options
  • Save isthatcentered/5a0f55680e50382b0332d96e1eda7598 to your computer and use it in GitHub Desktop.
Save isthatcentered/5a0f55680e50382b0332d96e1eda7598 to your computer and use it in GitHub Desktop.
Typescript / React Redux - Ensure all actions handled in switch case
type exampleReducerAction = Waffled | Pancaked | NOT_HANDLED_IN_SWITCH_CASE
function breakfastReducer( state: any, action: exampleReducerAction ): any
{
// Note, for some reason action.type doesn't work
switch ( action.type ) {
case "PancakedAction":
return "Gimme!"
case "WaffledAction":
return "Moar!"
// Because we do not handle the "NOT_HANDLED_IN_SWITCH_CASE" action
default:
// A vallue arrive into "ensureAllActionsHandled()"
ensureAllActionsHandled( action )
}
}
// But the function specifies it should get nothing by using the "never" type for it's param
function ensureAllActionsHandled( unhandledCase: never )
{
throw new class extends Error
{
message = `Case ${unhandledCase} should not have been reached`
name = `UnhandledCodeError`
}
}
// The rest doesn't matter
interface Pancaked
{
type: "PancakedAction"
// ...stuff
}
interface Waffled
{
type: "WaffledAction"
// ...stuff
}
interface NOT_HANDLED_IN_SWITCH_CASE
{
type: "UnhandledAction"
// ...stuff
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment