createAction
Generates an action creator for a specific action type.
// JavaScript
function createAction(type)// TypeScript
function createAction<T extends string | symbol | number>(
type: T
): BasicActionCreator<T>Details
createAction takes an action type value and returns an action creator which produces actions of that type.
For a version of the action creator which accepts a payload value and attaches the returned action, call the withPayload() method (e.g., createAction("…").withPayload().)
In addition to withPayload(), action creators returned by createAction() have the following properties:
type: The type value passed tocreateAction(). Removes the need for a separate action type constant, and allows other helpers such asonActionto inspect thetypevalue of the produced actions at runtime.matches(action): A method that returns true the the passed action has the sametypeas the ones produced by the action creator.
TypeScript Notes
.withPayload()is defined with a type parameter that specifies the payload type. You can override the default (any) by specifying the type parameter explicitly:const incrementBy = createAction('incrementBy').withPayload<number>();.matches()is defined as a type predicate. Using it in a condition allows the TypeScript compiler to narrow the type of passed action to the specific type of action returned by the action creator:if (incrementBy.matches(action)) { const amount = action.payload // Type is inferred to be `number` due to matches() }
Examples
Defining a basic action:
Defining an action with payload:
Specifying the action payload type (TypeScript):
See Also
Actions guide
Last updated