MCPcopy
hub / github.com/reduxjs/redux / simple

Function simple

test/typescript/reducers.ts:16–59  ·  test/typescript/reducers.ts::simple

* Simple reducer definition with no action shape checks. * Uses string comparison to determine action type. * * `AnyAction` type is used to allow action property access without requiring * type casting.

()

Source from the content-addressed store, hash-verified

14 * type casting.
15 */
16function simple() {
17 type State = number
18
19 const reducer: Reducer<State> = (state = 0, action) => {
20 if (action.type === class="st">'INCREMENT') {
21 const { count = 1 } = action
22 if (typeof count === class="st">'number') {
23 return state + count
24 }
25 }
26
27 if (action.type === class="st">'DECREMENT') {
28 const { count = 1 } = action
29 if (typeof count === class="st">'number') {
30 return state + count
31 }
32 }
33
34 return state
35 }
36
37 class="cm">// Reducer function accepts any object with `type` prop as action.
38 class="cm">// Any extra props are allowed too.
39 let s: State = reducer(undefined, { type: class="st">'init' })
40 s = reducer(s, { type: class="st">'INCREMENT' })
41 s = reducer(s, { type: class="st">'INCREMENT', count: 10 })
42 s = reducer(s, { type: class="st">'DECREMENT' })
43 s = reducer(s, { type: class="st">'DECREMENT', count: 10 })
44 s = reducer(s, { type: class="st">'SOME_OTHER_TYPE', someField: class="st">'value' })
45
46 class="cm">// State shape is strictly checked.
47 class="cm">// @ts-expect-error
48 reducer(class="st">'string', { type: class="st">'INCREMENT' })
49
50 class="cm">// Combined reducer also accepts any action.
51 const combined = combineReducers({ sub: reducer })
52
53 let cs: { sub: State } = combined(undefined, { type: class="st">'init' })
54 cs = combined(cs, { type: class="st">'INCREMENT', count: 10 })
55
56 class="cm">// Combined reducer's state is strictly checked.
57 class="cm">// @ts-expect-error
58 combined({ unknown: class="st">'' }, { type: class="st">'INCREMENT' })
59}
60
61/**
62 * Reducer definition using discriminated unions.

Callers

nothing calls this directly

Calls 2

combineReducersFunction · 0.85
reducerFunction · 0.70

Tested by

no test coverage detected