* Reducer definition using discriminated unions. * * See https://basarat.gitbooks.io/typescript/content/docs/types/discriminated-unions.html#redux
()
| 64 | * See https://basarat.gitbooks.io/typescript/content/docs/types/discriminated-unions.html#redux |
| 65 | */ |
| 66 | function discriminated() { |
| 67 | type State = number |
| 68 | |
| 69 | interface IncrementAction { |
| 70 | type: 'INCREMENT' |
| 71 | count?: number |
| 72 | } |
| 73 | |
| 74 | interface DecrementAction { |
| 75 | type: 'DECREMENT' |
| 76 | count?: number |
| 77 | } |
| 78 | |
| 79 | interface MultiplyAction { |
| 80 | type: 'MULTIPLY' |
| 81 | count?: number |
| 82 | } |
| 83 | |
| 84 | interface DivideAction { |
| 85 | type: 'DIVIDE' |
| 86 | count?: number |
| 87 | } |
| 88 | |
| 89 | // Union of all actions in the app. |
| 90 | type MyAction0 = IncrementAction | DecrementAction |
| 91 | type MyAction1 = MultiplyAction | DivideAction |
| 92 | |
| 93 | const reducer0: Reducer<State, MyAction0> = (state = 0, action) => { |
| 94 | if (action.type === 'INCREMENT') { |
| 95 | // Action shape is determined by `type` discriminator. |
| 96 | // @ts-expect-error |
| 97 | action.wrongField |
| 98 | |
| 99 | const { count = 1 } = action |
| 100 | |
| 101 | return state + count |
| 102 | } |
| 103 | |
| 104 | if (action.type === 'DECREMENT') { |
| 105 | // @ts-expect-error |
| 106 | action.wrongField |
| 107 | |
| 108 | const { count = 1 } = action |
| 109 | |
| 110 | return state - count |
| 111 | } |
| 112 | |
| 113 | return state |
| 114 | } |
| 115 | |
| 116 | const reducer1: Reducer<State, MyAction1> = (state = 0, action) => { |
| 117 | if (action.type === 'MULTIPLY') { |
| 118 | // @ts-expect-error |
| 119 | action.wrongField |
| 120 | |
| 121 | const { count = 1 } = action |
| 122 | |
| 123 | return state * count |
nothing calls this directly
no test coverage detected