Skip to content

Commit 2864e1a

Browse files
phryneasmarkerikson
authored andcommitted
add docs for createAction.match (#244)
* add docs for createAction.match * Update createAction.md
1 parent 9a18633 commit 2864e1a

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

docs/api/createAction.md

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,3 +136,40 @@ const counterReducer = createReducer(0, {
136136
```
137137
138138
For this reason, **we strongly recommend you to only use string action types**.
139+
140+
## actionCreator.match
141+
142+
Every generated actionCreator has a `.match(action)` method that can be used to determine if the passed action is of the same type as an action that would be created by the action creator.
143+
144+
This has different uses:
145+
146+
### As a TypeScript TypeGuard
147+
148+
This `match` method is a [TypeScript type guard](https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards) and can be used to discriminate the `payload` type of an action.
149+
150+
This behavior can be particularly useful when used in custom middlewares, where manual casts might be neccessary otherwise.
151+
152+
```typescript
153+
const increment = createAction<number>('INCREMENT')
154+
155+
function someFunction(action: Action) {
156+
// accessing action.payload would result in an error here
157+
if (increment.match(action)) {
158+
// action.payload can be used as `number` here
159+
}
160+
}
161+
```
162+
163+
### With redux-observable
164+
165+
The `match` method can also be used as a filter method, which makes it powerful when used with redux-observable:
166+
167+
```typescript
168+
const increment = createAction<number>('INCREMENT')
169+
170+
export const epic = (actions$: Observable<Action>) =>
171+
actions$.filter(increment.match).map(action => {
172+
// action.payload can be safely used as number here (and will also be correctly inferred by TypeScript)
173+
// ...
174+
})
175+
```

0 commit comments

Comments
 (0)