UNPKG

16.6 kBTypeScriptView Raw
1/**
2 * An *action* is a plain object that represents an intention to change the
3 * state. Actions are the only way to get data into the store. Any data,
4 * whether from UI events, network callbacks, or other sources such as
5 * WebSockets needs to eventually be dispatched as actions.
6 *
7 * Actions must have a `type` field that indicates the type of action being
8 * performed. Types can be defined as constants and imported from another
9 * module. It's better to use strings for `type` than Symbols because strings
10 * are serializable.
11 *
12 * Other than `type`, the structure of an action object is really up to you.
13 * If you're interested, check out Flux Standard Action for recommendations on
14 * how actions should be constructed.
15 */
16export interface Action {
17 type: any;
18}
19
20
21/* reducers */
22
23/**
24 * A *reducer* (also called a *reducing function*) is a function that accepts
25 * an accumulation and a value and returns a new accumulation. They are used
26 * to reduce a collection of values down to a single value
27 *
28 * Reducers are not unique to Redux—they are a fundamental concept in
29 * functional programming. Even most non-functional languages, like
30 * JavaScript, have a built-in API for reducing. In JavaScript, it's
31 * `Array.prototype.reduce()`.
32 *
33 * In Redux, the accumulated value is the state object, and the values being
34 * accumulated are actions. Reducers calculate a new state given the previous
35 * state and an action. They must be *pure functions*—functions that return
36 * the exact same output for given inputs. They should also be free of
37 * side-effects. This is what enables exciting features like hot reloading and
38 * time travel.
39 *
40 * Reducers are the most important concept in Redux.
41 *
42 * *Do not put API calls into reducers.*
43 *
44 * @template S State object type.
45 */
46export type Reducer<S> = <A extends Action>(state: S, action: A) => S;
47
48/**
49 * Object whose values correspond to different reducer functions.
50 */
51export interface ReducersMapObject {
52 [key: string]: Reducer<any>;
53}
54
55/**
56 * Turns an object whose values are different reducer functions, into a single
57 * reducer function. It will call every child reducer, and gather their results
58 * into a single state object, whose keys correspond to the keys of the passed
59 * reducer functions.
60 *
61 * @template S Combined state object type.
62 *
63 * @param reducers An object whose values correspond to different reducer
64 * functions that need to be combined into one. One handy way to obtain it
65 * is to use ES6 `import * as reducers` syntax. The reducers may never
66 * return undefined for any action. Instead, they should return their
67 * initial state if the state passed to them was undefined, and the current
68 * state for any unrecognized action.
69 *
70 * @returns A reducer function that invokes every reducer inside the passed
71 * object, and builds a state object with the same shape.
72 */
73export function combineReducers<S>(reducers: ReducersMapObject): Reducer<S>;
74
75
76/* store */
77
78/**
79 * A *dispatching function* (or simply *dispatch function*) is a function that
80 * accepts an action or an async action; it then may or may not dispatch one
81 * or more actions to the store.
82 *
83 * We must distinguish between dispatching functions in general and the base
84 * `dispatch` function provided by the store instance without any middleware.
85 *
86 * The base dispatch function *always* synchronously sends an action to the
87 * store's reducer, along with the previous state returned by the store, to
88 * calculate a new state. It expects actions to be plain objects ready to be
89 * consumed by the reducer.
90 *
91 * Middleware wraps the base dispatch function. It allows the dispatch
92 * function to handle async actions in addition to actions. Middleware may
93 * transform, delay, ignore, or otherwise interpret actions or async actions
94 * before passing them to the next middleware.
95 */
96export interface Dispatch<S> {
97 <A extends Action>(action: A): A;
98}
99
100/**
101 * Function to remove listener added by `Store.subscribe()`.
102 */
103export interface Unsubscribe {
104 (): void;
105}
106
107/**
108 * A store is an object that holds the application's state tree.
109 * There should only be a single store in a Redux app, as the composition
110 * happens on the reducer level.
111 *
112 * @template S State object type.
113 */
114export interface Store<S> {
115 /**
116 * Dispatches an action. It is the only way to trigger a state change.
117 *
118 * The `reducer` function, used to create the store, will be called with the
119 * current state tree and the given `action`. Its return value will be
120 * considered the **next** state of the tree, and the change listeners will
121 * be notified.
122 *
123 * The base implementation only supports plain object actions. If you want
124 * to dispatch a Promise, an Observable, a thunk, or something else, you
125 * need to wrap your store creating function into the corresponding
126 * middleware. For example, see the documentation for the `redux-thunk`
127 * package. Even the middleware will eventually dispatch plain object
128 * actions using this method.
129 *
130 * @param action A plain object representing “what changed”. It is a good
131 * idea to keep actions serializable so you can record and replay user
132 * sessions, or use the time travelling `redux-devtools`. An action must
133 * have a `type` property which may not be `undefined`. It is a good idea
134 * to use string constants for action types.
135 *
136 * @returns For convenience, the same action object you dispatched.
137 *
138 * Note that, if you use a custom middleware, it may wrap `dispatch()` to
139 * return something else (for example, a Promise you can await).
140 */
141 dispatch: Dispatch<S>;
142
143 /**
144 * Reads the state tree managed by the store.
145 *
146 * @returns The current state tree of your application.
147 */
148 getState(): S;
149
150 /**
151 * Adds a change listener. It will be called any time an action is
152 * dispatched, and some part of the state tree may potentially have changed.
153 * You may then call `getState()` to read the current state tree inside the
154 * callback.
155 *
156 * You may call `dispatch()` from a change listener, with the following
157 * caveats:
158 *
159 * 1. The subscriptions are snapshotted just before every `dispatch()` call.
160 * If you subscribe or unsubscribe while the listeners are being invoked,
161 * this will not have any effect on the `dispatch()` that is currently in
162 * progress. However, the next `dispatch()` call, whether nested or not,
163 * will use a more recent snapshot of the subscription list.
164 *
165 * 2. The listener should not expect to see all states changes, as the state
166 * might have been updated multiple times during a nested `dispatch()` before
167 * the listener is called. It is, however, guaranteed that all subscribers
168 * registered before the `dispatch()` started will be called with the latest
169 * state by the time it exits.
170 *
171 * @param listener A callback to be invoked on every dispatch.
172 * @returns A function to remove this change listener.
173 */
174 subscribe(listener: () => void): Unsubscribe;
175
176 /**
177 * Replaces the reducer currently used by the store to calculate the state.
178 *
179 * You might need this if your app implements code splitting and you want to
180 * load some of the reducers dynamically. You might also need this if you
181 * implement a hot reloading mechanism for Redux.
182 *
183 * @param nextReducer The reducer for the store to use instead.
184 */
185 replaceReducer(nextReducer: Reducer<S>): void;
186}
187
188/**
189 * A store creator is a function that creates a Redux store. Like with
190 * dispatching function, we must distinguish the base store creator,
191 * `createStore(reducer, preloadedState)` exported from the Redux package, from
192 * store creators that are returned from the store enhancers.
193 *
194 * @template S State object type.
195 */
196export interface StoreCreator {
197 <S>(reducer: Reducer<S>, enhancer?: StoreEnhancer<S>): Store<S>;
198 <S>(reducer: Reducer<S>, preloadedState: S, enhancer?: StoreEnhancer<S>): Store<S>;
199}
200
201/**
202 * A store enhancer is a higher-order function that composes a store creator
203 * to return a new, enhanced store creator. This is similar to middleware in
204 * that it allows you to alter the store interface in a composable way.
205 *
206 * Store enhancers are much the same concept as higher-order components in
207 * React, which are also occasionally called “component enhancers”.
208 *
209 * Because a store is not an instance, but rather a plain-object collection of
210 * functions, copies can be easily created and modified without mutating the
211 * original store. There is an example in `compose` documentation
212 * demonstrating that.
213 *
214 * Most likely you'll never write a store enhancer, but you may use the one
215 * provided by the developer tools. It is what makes time travel possible
216 * without the app being aware it is happening. Amusingly, the Redux
217 * middleware implementation is itself a store enhancer.
218 */
219export type StoreEnhancer<S> = (next: StoreEnhancerStoreCreator<S>) => StoreEnhancerStoreCreator<S>;
220export type GenericStoreEnhancer = <S>(next: StoreEnhancerStoreCreator<S>) => StoreEnhancerStoreCreator<S>;
221export type StoreEnhancerStoreCreator<S> = (reducer: Reducer<S>, preloadedState?: S) => Store<S>;
222
223/**
224 * Creates a Redux store that holds the state tree.
225 * The only way to change the data in the store is to call `dispatch()` on it.
226 *
227 * There should only be a single store in your app. To specify how different
228 * parts of the state tree respond to actions, you may combine several
229 * reducers
230 * into a single reducer function by using `combineReducers`.
231 *
232 * @template S State object type.
233 *
234 * @param reducer A function that returns the next state tree, given the
235 * current state tree and the action to handle.
236 *
237 * @param [preloadedState] The initial state. You may optionally specify it to
238 * hydrate the state from the server in universal apps, or to restore a
239 * previously serialized user session. If you use `combineReducers` to
240 * produce the root reducer function, this must be an object with the same
241 * shape as `combineReducers` keys.
242 *
243 * @param [enhancer] The store enhancer. You may optionally specify it to
244 * enhance the store with third-party capabilities such as middleware, time
245 * travel, persistence, etc. The only store enhancer that ships with Redux
246 * is `applyMiddleware()`.
247 *
248 * @returns A Redux store that lets you read the state, dispatch actions and
249 * subscribe to changes.
250 */
251export const createStore: StoreCreator;
252
253
254/* middleware */
255
256export interface MiddlewareAPI<S> {
257 dispatch: Dispatch<S>;
258 getState(): S;
259}
260
261/**
262 * A middleware is a higher-order function that composes a dispatch function
263 * to return a new dispatch function. It often turns async actions into
264 * actions.
265 *
266 * Middleware is composable using function composition. It is useful for
267 * logging actions, performing side effects like routing, or turning an
268 * asynchronous API call into a series of synchronous actions.
269 */
270export interface Middleware {
271 <S>(api: MiddlewareAPI<S>): (next: Dispatch<S>) => Dispatch<S>;
272}
273
274/**
275 * Creates a store enhancer that applies middleware to the dispatch method
276 * of the Redux store. This is handy for a variety of tasks, such as
277 * expressing asynchronous actions in a concise manner, or logging every
278 * action payload.
279 *
280 * See `redux-thunk` package as an example of the Redux middleware.
281 *
282 * Because middleware is potentially asynchronous, this should be the first
283 * store enhancer in the composition chain.
284 *
285 * Note that each middleware will be given the `dispatch` and `getState`
286 * functions as named arguments.
287 *
288 * @param middlewares The middleware chain to be applied.
289 * @returns A store enhancer applying the middleware.
290 */
291export function applyMiddleware(...middlewares: Middleware[]): GenericStoreEnhancer;
292
293
294/* action creators */
295
296/**
297 * An *action creator* is, quite simply, a function that creates an action. Do
298 * not confuse the two terms—again, an action is a payload of information, and
299 * an action creator is a factory that creates an action.
300 *
301 * Calling an action creator only produces an action, but does not dispatch
302 * it. You need to call the store's `dispatch` function to actually cause the
303 * mutation. Sometimes we say *bound action creators* to mean functions that
304 * call an action creator and immediately dispatch its result to a specific
305 * store instance.
306 *
307 * If an action creator needs to read the current state, perform an API call,
308 * or cause a side effect, like a routing transition, it should return an
309 * async action instead of an action.
310 *
311 * @template A Returned action type.
312 */
313export interface ActionCreator<A> {
314 (...args: any[]): A;
315}
316
317/**
318 * Object whose values are action creator functions.
319 */
320export interface ActionCreatorsMapObject {
321 [key: string]: ActionCreator<any>;
322}
323
324/**
325 * Turns an object whose values are action creators, into an object with the
326 * same keys, but with every function wrapped into a `dispatch` call so they
327 * may be invoked directly. This is just a convenience method, as you can call
328 * `store.dispatch(MyActionCreators.doSomething())` yourself just fine.
329 *
330 * For convenience, you can also pass a single function as the first argument,
331 * and get a function in return.
332 *
333 * @param actionCreator An object whose values are action creator functions.
334 * One handy way to obtain it is to use ES6 `import * as` syntax. You may
335 * also pass a single function.
336 *
337 * @param dispatch The `dispatch` function available on your Redux store.
338 *
339 * @returns The object mimicking the original object, but with every action
340 * creator wrapped into the `dispatch` call. If you passed a function as
341 * `actionCreator`, the return value will also be a single function.
342 */
343export function bindActionCreators<A extends ActionCreator<any>>(actionCreator: A, dispatch: Dispatch<any>): A;
344
345export function bindActionCreators<
346 A extends ActionCreator<any>,
347 B extends ActionCreator<any>
348 >(actionCreator: A, dispatch: Dispatch<any>): B;
349
350export function bindActionCreators<M extends ActionCreatorsMapObject>(actionCreators: M, dispatch: Dispatch<any>): M;
351
352export function bindActionCreators<
353 M extends ActionCreatorsMapObject,
354 N extends ActionCreatorsMapObject
355 >(actionCreators: M, dispatch: Dispatch<any>): N;
356
357
358/* compose */
359
360type Func0<R> = () => R;
361type Func1<T1, R> = (a1: T1) => R;
362type Func2<T1, T2, R> = (a1: T1, a2: T2) => R;
363type Func3<T1, T2, T3, R> = (a1: T1, a2: T2, a3: T3, ...args: any[]) => R;
364
365/**
366 * Composes single-argument functions from right to left. The rightmost
367 * function can take multiple arguments as it provides the signature for the
368 * resulting composite function.
369 *
370 * @param funcs The functions to compose.
371 * @returns R function obtained by composing the argument functions from right
372 * to left. For example, `compose(f, g, h)` is identical to doing
373 * `(...args) => f(g(h(...args)))`.
374 */
375export function compose(): <R>(a: R) => R;
376
377export function compose<F extends Function>(f: F): F;
378
379/* two functions */
380export function compose<A, R>(
381 f1: (b: A) => R, f2: Func0<A>
382): Func0<R>;
383export function compose<A, T1, R>(
384 f1: (b: A) => R, f2: Func1<T1, A>
385): Func1<T1, R>;
386export function compose<A, T1, T2, R>(
387 f1: (b: A) => R, f2: Func2<T1, T2, A>
388): Func2<T1, T2, R>;
389export function compose<A, T1, T2, T3, R>(
390 f1: (b: A) => R, f2: Func3<T1, T2, T3, A>
391): Func3<T1, T2, T3, R>;
392
393/* three functions */
394export function compose<A, B, R>(
395 f1: (b: B) => R, f2: (a: A) => B, f3: Func0<A>
396): Func0<R>;
397export function compose<A, B, T1, R>(
398 f1: (b: B) => R, f2: (a: A) => B, f3: Func1<T1, A>
399): Func1<T1, R>;
400export function compose<A, B, T1, T2, R>(
401 f1: (b: B) => R, f2: (a: A) => B, f3: Func2<T1, T2, A>
402): Func2<T1, T2, R>;
403export function compose<A, B, T1, T2, T3, R>(
404 f1: (b: B) => R, f2: (a: A) => B, f3: Func3<T1, T2, T3, A>
405): Func3<T1, T2, T3, R>;
406
407/* four functions */
408export function compose<A, B, C, R>(
409 f1: (b: C) => R, f2: (a: B) => C, f3: (a: A) => B, f4: Func0<A>
410): Func0<R>;
411export function compose<A, B, C, T1, R>(
412 f1: (b: C) => R, f2: (a: B) => C, f3: (a: A) => B, f4: Func1<T1, A>
413): Func1<T1, R>;
414export function compose<A, B, C, T1, T2, R>(
415 f1: (b: C) => R, f2: (a: B) => C, f3: (a: A) => B, f4: Func2<T1, T2, A>
416): Func2<T1, T2, R>;
417export function compose<A, B, C, T1, T2, T3, R>(
418 f1: (b: C) => R, f2: (a: B) => C, f3: (a: A) => B, f4: Func3<T1, T2, T3, A>
419): Func3<T1, T2, T3, R>;
420
421/* rest */
422export function compose<A, B, C, R>(
423 f1: (b: C) => R, f2: (a: B) => C, f3: (a: A) => B,
424 ...funcs: Function[]
425): (...args: any[]) => R;