UNPKG

24.2 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 *
16 * @template T the type of the action's `type` tag.
17 */
18export interface Action<T = any> {
19 type: T
20}
21
22/**
23 * An Action type which accepts any other properties.
24 * This is mainly for the use of the `Reducer` type.
25 * This is not part of `Action` itself to prevent types that extend `Action` from
26 * having an index signature.
27 */
28export interface AnyAction extends Action {
29 // Allows any extra properties to be defined in an action.
30 [extraProps: string]: any
31}
32
33/**
34 * Internal "virtual" symbol used to make the `CombinedState` type unique.
35 */
36declare const $CombinedState: unique symbol
37
38/**
39 * State base type for reducers created with `combineReducers()`.
40 *
41 * This type allows the `createStore()` method to infer which levels of the
42 * preloaded state can be partial.
43 *
44 * Because Typescript is really duck-typed, a type needs to have some
45 * identifying property to differentiate it from other types with matching
46 * prototypes for type checking purposes. That's why this type has the
47 * `$CombinedState` symbol property. Without the property, this type would
48 * match any object. The symbol doesn't really exist because it's an internal
49 * (i.e. not exported), and internally we never check its value. Since it's a
50 * symbol property, it's not expected to be unumerable, and the value is
51 * typed as always undefined, so its never expected to have a meaningful
52 * value anyway. It just makes this type distinquishable from plain `{}`.
53 */
54interface EmptyObject {
55 readonly [$CombinedState]?: undefined
56}
57export type CombinedState<S> = EmptyObject & S
58
59/**
60 * Recursively makes combined state objects partial. Only combined state _root
61 * objects_ (i.e. the generated higher level object with keys mapping to
62 * individual reducers) are partial.
63 */
64export type PreloadedState<S> = Required<S> extends EmptyObject
65 ? S extends CombinedState<infer S1>
66 ? {
67 [K in keyof S1]?: S1[K] extends object ? PreloadedState<S1[K]> : S1[K]
68 }
69 : never
70 : {
71 [K in keyof S]: S[K] extends string | number | boolean | symbol
72 ? S[K]
73 : PreloadedState<S[K]>
74 }
75
76/* reducers */
77
78/**
79 * A *reducer* (also called a *reducing function*) is a function that accepts
80 * an accumulation and a value and returns a new accumulation. They are used
81 * to reduce a collection of values down to a single value
82 *
83 * Reducers are not unique to Redux—they are a fundamental concept in
84 * functional programming. Even most non-functional languages, like
85 * JavaScript, have a built-in API for reducing. In JavaScript, it's
86 * `Array.prototype.reduce()`.
87 *
88 * In Redux, the accumulated value is the state object, and the values being
89 * accumulated are actions. Reducers calculate a new state given the previous
90 * state and an action. They must be *pure functions*—functions that return
91 * the exact same output for given inputs. They should also be free of
92 * side-effects. This is what enables exciting features like hot reloading and
93 * time travel.
94 *
95 * Reducers are the most important concept in Redux.
96 *
97 * *Do not put API calls into reducers.*
98 *
99 * @template S The type of state consumed and produced by this reducer.
100 * @template A The type of actions the reducer can potentially respond to.
101 */
102export type Reducer<S = any, A extends Action = AnyAction> = (
103 state: S | undefined,
104 action: A
105) => S
106
107/**
108 * Object whose values correspond to different reducer functions.
109 *
110 * @template A The type of actions the reducers can potentially respond to.
111 */
112export type ReducersMapObject<S = any, A extends Action = Action> = {
113 [K in keyof S]: Reducer<S[K], A>
114}
115
116/**
117 * Infer a combined state shape from a `ReducersMapObject`.
118 *
119 * @template M Object map of reducers as provided to `combineReducers(map: M)`.
120 */
121export type StateFromReducersMapObject<M> = M extends ReducersMapObject<
122 any,
123 any
124>
125 ? { [P in keyof M]: M[P] extends Reducer<infer S, any> ? S : never }
126 : never
127
128/**
129 * Infer reducer union type from a `ReducersMapObject`.
130 *
131 * @template M Object map of reducers as provided to `combineReducers(map: M)`.
132 */
133export type ReducerFromReducersMapObject<M> = M extends {
134 [P in keyof M]: infer R
135}
136 ? R extends Reducer<any, any>
137 ? R
138 : never
139 : never
140
141/**
142 * Infer action type from a reducer function.
143 *
144 * @template R Type of reducer.
145 */
146export type ActionFromReducer<R> = R extends Reducer<any, infer A> ? A : never
147
148/**
149 * Infer action union type from a `ReducersMapObject`.
150 *
151 * @template M Object map of reducers as provided to `combineReducers(map: M)`.
152 */
153export type ActionFromReducersMapObject<M> = M extends ReducersMapObject<
154 any,
155 any
156>
157 ? ActionFromReducer<ReducerFromReducersMapObject<M>>
158 : never
159
160/**
161 * Turns an object whose values are different reducer functions, into a single
162 * reducer function. It will call every child reducer, and gather their results
163 * into a single state object, whose keys correspond to the keys of the passed
164 * reducer functions.
165 *
166 * @template S Combined state object type.
167 *
168 * @param reducers An object whose values correspond to different reducer
169 * functions that need to be combined into one. One handy way to obtain it
170 * is to use ES6 `import * as reducers` syntax. The reducers may never
171 * return undefined for any action. Instead, they should return their
172 * initial state if the state passed to them was undefined, and the current
173 * state for any unrecognized action.
174 *
175 * @returns A reducer function that invokes every reducer inside the passed
176 * object, and builds a state object with the same shape.
177 */
178export function combineReducers<S>(
179 reducers: ReducersMapObject<S, any>
180): Reducer<CombinedState<S>>
181export function combineReducers<S, A extends Action = AnyAction>(
182 reducers: ReducersMapObject<S, A>
183): Reducer<CombinedState<S>, A>
184export function combineReducers<M extends ReducersMapObject<any, any>>(
185 reducers: M
186): Reducer<
187 CombinedState<StateFromReducersMapObject<M>>,
188 ActionFromReducersMapObject<M>
189>
190
191/* store */
192
193/**
194 * A *dispatching function* (or simply *dispatch function*) is a function that
195 * accepts an action or an async action; it then may or may not dispatch one
196 * or more actions to the store.
197 *
198 * We must distinguish between dispatching functions in general and the base
199 * `dispatch` function provided by the store instance without any middleware.
200 *
201 * The base dispatch function *always* synchronously sends an action to the
202 * store's reducer, along with the previous state returned by the store, to
203 * calculate a new state. It expects actions to be plain objects ready to be
204 * consumed by the reducer.
205 *
206 * Middleware wraps the base dispatch function. It allows the dispatch
207 * function to handle async actions in addition to actions. Middleware may
208 * transform, delay, ignore, or otherwise interpret actions or async actions
209 * before passing them to the next middleware.
210 *
211 * @template A The type of things (actions or otherwise) which may be
212 * dispatched.
213 */
214export interface Dispatch<A extends Action = AnyAction> {
215 <T extends A>(action: T): T
216}
217
218/**
219 * Function to remove listener added by `Store.subscribe()`.
220 */
221export interface Unsubscribe {
222 (): void
223}
224
225declare global {
226 interface SymbolConstructor {
227 readonly observable: symbol
228 }
229}
230
231/**
232 * A minimal observable of state changes.
233 * For more information, see the observable proposal:
234 * https://github.com/tc39/proposal-observable
235 */
236export type Observable<T> = {
237 /**
238 * The minimal observable subscription method.
239 * @param {Object} observer Any object that can be used as an observer.
240 * The observer object should have a `next` method.
241 * @returns {subscription} An object with an `unsubscribe` method that can
242 * be used to unsubscribe the observable from the store, and prevent further
243 * emission of values from the observable.
244 */
245 subscribe: (observer: Observer<T>) => { unsubscribe: Unsubscribe }
246 [Symbol.observable](): Observable<T>
247}
248
249/**
250 * An Observer is used to receive data from an Observable, and is supplied as
251 * an argument to subscribe.
252 */
253export type Observer<T> = {
254 next?(value: T): void
255}
256
257/**
258 * A store is an object that holds the application's state tree.
259 * There should only be a single store in a Redux app, as the composition
260 * happens on the reducer level.
261 *
262 * @template S The type of state held by this store.
263 * @template A the type of actions which may be dispatched by this store.
264 */
265export interface Store<S = any, A extends Action = AnyAction> {
266 /**
267 * Dispatches an action. It is the only way to trigger a state change.
268 *
269 * The `reducer` function, used to create the store, will be called with the
270 * current state tree and the given `action`. Its return value will be
271 * considered the **next** state of the tree, and the change listeners will
272 * be notified.
273 *
274 * The base implementation only supports plain object actions. If you want
275 * to dispatch a Promise, an Observable, a thunk, or something else, you
276 * need to wrap your store creating function into the corresponding
277 * middleware. For example, see the documentation for the `redux-thunk`
278 * package. Even the middleware will eventually dispatch plain object
279 * actions using this method.
280 *
281 * @param action A plain object representing “what changed”. It is a good
282 * idea to keep actions serializable so you can record and replay user
283 * sessions, or use the time travelling `redux-devtools`. An action must
284 * have a `type` property which may not be `undefined`. It is a good idea
285 * to use string constants for action types.
286 *
287 * @returns For convenience, the same action object you dispatched.
288 *
289 * Note that, if you use a custom middleware, it may wrap `dispatch()` to
290 * return something else (for example, a Promise you can await).
291 */
292 dispatch: Dispatch<A>
293
294 /**
295 * Reads the state tree managed by the store.
296 *
297 * @returns The current state tree of your application.
298 */
299 getState(): S
300
301 /**
302 * Adds a change listener. It will be called any time an action is
303 * dispatched, and some part of the state tree may potentially have changed.
304 * You may then call `getState()` to read the current state tree inside the
305 * callback.
306 *
307 * You may call `dispatch()` from a change listener, with the following
308 * caveats:
309 *
310 * 1. The subscriptions are snapshotted just before every `dispatch()` call.
311 * If you subscribe or unsubscribe while the listeners are being invoked,
312 * this will not have any effect on the `dispatch()` that is currently in
313 * progress. However, the next `dispatch()` call, whether nested or not,
314 * will use a more recent snapshot of the subscription list.
315 *
316 * 2. The listener should not expect to see all states changes, as the state
317 * might have been updated multiple times during a nested `dispatch()` before
318 * the listener is called. It is, however, guaranteed that all subscribers
319 * registered before the `dispatch()` started will be called with the latest
320 * state by the time it exits.
321 *
322 * @param listener A callback to be invoked on every dispatch.
323 * @returns A function to remove this change listener.
324 */
325 subscribe(listener: () => void): Unsubscribe
326
327 /**
328 * Replaces the reducer currently used by the store to calculate the state.
329 *
330 * You might need this if your app implements code splitting and you want to
331 * load some of the reducers dynamically. You might also need this if you
332 * implement a hot reloading mechanism for Redux.
333 *
334 * @param nextReducer The reducer for the store to use instead.
335 */
336 replaceReducer(nextReducer: Reducer<S, A>): void
337
338 /**
339 * Interoperability point for observable/reactive libraries.
340 * @returns {observable} A minimal observable of state changes.
341 * For more information, see the observable proposal:
342 * https://github.com/tc39/proposal-observable
343 */
344 [Symbol.observable](): Observable<S>
345}
346
347export type DeepPartial<T> = {
348 [K in keyof T]?: T[K] extends object ? DeepPartial<T[K]> : T[K]
349}
350
351/**
352 * A store creator is a function that creates a Redux store. Like with
353 * dispatching function, we must distinguish the base store creator,
354 * `createStore(reducer, preloadedState)` exported from the Redux package, from
355 * store creators that are returned from the store enhancers.
356 *
357 * @template S The type of state to be held by the store.
358 * @template A The type of actions which may be dispatched.
359 * @template Ext Store extension that is mixed in to the Store type.
360 * @template StateExt State extension that is mixed into the state type.
361 */
362export interface StoreCreator {
363 <S, A extends Action, Ext, StateExt>(
364 reducer: Reducer<S, A>,
365 enhancer?: StoreEnhancer<Ext, StateExt>
366 ): Store<S & StateExt, A> & Ext
367 <S, A extends Action, Ext, StateExt>(
368 reducer: Reducer<S, A>,
369 preloadedState?: PreloadedState<S>,
370 enhancer?: StoreEnhancer<Ext>
371 ): Store<S & StateExt, A> & Ext
372}
373
374/**
375 * Creates a Redux store that holds the state tree.
376 * The only way to change the data in the store is to call `dispatch()` on it.
377 *
378 * There should only be a single store in your app. To specify how different
379 * parts of the state tree respond to actions, you may combine several
380 * reducers
381 * into a single reducer function by using `combineReducers`.
382 *
383 * @template S State object type.
384 *
385 * @param reducer A function that returns the next state tree, given the
386 * current state tree and the action to handle.
387 *
388 * @param [preloadedState] The initial state. You may optionally specify it to
389 * hydrate the state from the server in universal apps, or to restore a
390 * previously serialized user session. If you use `combineReducers` to
391 * produce the root reducer function, this must be an object with the same
392 * shape as `combineReducers` keys.
393 *
394 * @param [enhancer] The store enhancer. You may optionally specify it to
395 * enhance the store with third-party capabilities such as middleware, time
396 * travel, persistence, etc. The only store enhancer that ships with Redux
397 * is `applyMiddleware()`.
398 *
399 * @returns A Redux store that lets you read the state, dispatch actions and
400 * subscribe to changes.
401 */
402export const createStore: StoreCreator
403
404/**
405 * A store enhancer is a higher-order function that composes a store creator
406 * to return a new, enhanced store creator. This is similar to middleware in
407 * that it allows you to alter the store interface in a composable way.
408 *
409 * Store enhancers are much the same concept as higher-order components in
410 * React, which are also occasionally called “component enhancers”.
411 *
412 * Because a store is not an instance, but rather a plain-object collection of
413 * functions, copies can be easily created and modified without mutating the
414 * original store. There is an example in `compose` documentation
415 * demonstrating that.
416 *
417 * Most likely you'll never write a store enhancer, but you may use the one
418 * provided by the developer tools. It is what makes time travel possible
419 * without the app being aware it is happening. Amusingly, the Redux
420 * middleware implementation is itself a store enhancer.
421 *
422 * @template Ext Store extension that is mixed into the Store type.
423 * @template StateExt State extension that is mixed into the state type.
424 */
425export type StoreEnhancer<Ext = {}, StateExt = {}> = (
426 next: StoreEnhancerStoreCreator
427) => StoreEnhancerStoreCreator<Ext, StateExt>
428export type StoreEnhancerStoreCreator<Ext = {}, StateExt = {}> = <
429 S = any,
430 A extends Action = AnyAction
431>(
432 reducer: Reducer<S, A>,
433 preloadedState?: PreloadedState<S>
434) => Store<S & StateExt, A> & Ext
435
436/* middleware */
437
438export interface MiddlewareAPI<D extends Dispatch = Dispatch, S = any> {
439 dispatch: D
440 getState(): S
441}
442
443/**
444 * A middleware is a higher-order function that composes a dispatch function
445 * to return a new dispatch function. It often turns async actions into
446 * actions.
447 *
448 * Middleware is composable using function composition. It is useful for
449 * logging actions, performing side effects like routing, or turning an
450 * asynchronous API call into a series of synchronous actions.
451 *
452 * @template DispatchExt Extra Dispatch signature added by this middleware.
453 * @template S The type of the state supported by this middleware.
454 * @template D The type of Dispatch of the store where this middleware is
455 * installed.
456 */
457export interface Middleware<
458 DispatchExt = {},
459 S = any,
460 D extends Dispatch = Dispatch
461> {
462 (api: MiddlewareAPI<D, S>): (
463 next: Dispatch<AnyAction>
464 ) => (action: any) => any
465}
466
467/**
468 * Creates a store enhancer that applies middleware to the dispatch method
469 * of the Redux store. This is handy for a variety of tasks, such as
470 * expressing asynchronous actions in a concise manner, or logging every
471 * action payload.
472 *
473 * See `redux-thunk` package as an example of the Redux middleware.
474 *
475 * Because middleware is potentially asynchronous, this should be the first
476 * store enhancer in the composition chain.
477 *
478 * Note that each middleware will be given the `dispatch` and `getState`
479 * functions as named arguments.
480 *
481 * @param middlewares The middleware chain to be applied.
482 * @returns A store enhancer applying the middleware.
483 *
484 * @template Ext Dispatch signature added by a middleware.
485 * @template S The type of the state supported by a middleware.
486 */
487export function applyMiddleware(): StoreEnhancer
488export function applyMiddleware<Ext1, S>(
489 middleware1: Middleware<Ext1, S, any>
490): StoreEnhancer<{ dispatch: Ext1 }>
491export function applyMiddleware<Ext1, Ext2, S>(
492 middleware1: Middleware<Ext1, S, any>,
493 middleware2: Middleware<Ext2, S, any>
494): StoreEnhancer<{ dispatch: Ext1 & Ext2 }>
495export function applyMiddleware<Ext1, Ext2, Ext3, S>(
496 middleware1: Middleware<Ext1, S, any>,
497 middleware2: Middleware<Ext2, S, any>,
498 middleware3: Middleware<Ext3, S, any>
499): StoreEnhancer<{ dispatch: Ext1 & Ext2 & Ext3 }>
500export function applyMiddleware<Ext1, Ext2, Ext3, Ext4, S>(
501 middleware1: Middleware<Ext1, S, any>,
502 middleware2: Middleware<Ext2, S, any>,
503 middleware3: Middleware<Ext3, S, any>,
504 middleware4: Middleware<Ext4, S, any>
505): StoreEnhancer<{ dispatch: Ext1 & Ext2 & Ext3 & Ext4 }>
506export function applyMiddleware<Ext1, Ext2, Ext3, Ext4, Ext5, S>(
507 middleware1: Middleware<Ext1, S, any>,
508 middleware2: Middleware<Ext2, S, any>,
509 middleware3: Middleware<Ext3, S, any>,
510 middleware4: Middleware<Ext4, S, any>,
511 middleware5: Middleware<Ext5, S, any>
512): StoreEnhancer<{ dispatch: Ext1 & Ext2 & Ext3 & Ext4 & Ext5 }>
513export function applyMiddleware<Ext, S = any>(
514 ...middlewares: Middleware<any, S, any>[]
515): StoreEnhancer<{ dispatch: Ext }>
516
517/* action creators */
518
519/**
520 * An *action creator* is, quite simply, a function that creates an action. Do
521 * not confuse the two termsagain, an action is a payload of information, and
522 * an action creator is a factory that creates an action.
523 *
524 * Calling an action creator only produces an action, but does not dispatch
525 * it. You need to call the store's `dispatch` function to actually cause the
526 * mutation. Sometimes we say *bound action creators* to mean functions that
527 * call an action creator and immediately dispatch its result to a specific
528 * store instance.
529 *
530 * If an action creator needs to read the current state, perform an API call,
531 * or cause a side effect, like a routing transition, it should return an
532 * async action instead of an action.
533 *
534 * @template A Returned action type.
535 */
536export interface ActionCreator<A> {
537 (...args: any[]): A
538}
539
540/**
541 * Object whose values are action creator functions.
542 */
543export interface ActionCreatorsMapObject<A = any> {
544 [key: string]: ActionCreator<A>
545}
546
547/**
548 * Turns an object whose values are action creators, into an object with the
549 * same keys, but with every function wrapped into a `dispatch` call so they
550 * may be invoked directly. This is just a convenience method, as you can call
551 * `store.dispatch(MyActionCreators.doSomething())` yourself just fine.
552 *
553 * For convenience, you can also pass a single function as the first argument,
554 * and get a function in return.
555 *
556 * @param actionCreator An object whose values are action creator functions.
557 * One handy way to obtain it is to use ES6 `import * as` syntax. You may
558 * also pass a single function.
559 *
560 * @param dispatch The `dispatch` function available on your Redux store.
561 *
562 * @returns The object mimicking the original object, but with every action
563 * creator wrapped into the `dispatch` call. If you passed a function as
564 * `actionCreator`, the return value will also be a single function.
565 */
566export function bindActionCreators<A, C extends ActionCreator<A>>(
567 actionCreator: C,
568 dispatch: Dispatch
569): C
570
571export function bindActionCreators<
572 A extends ActionCreator<any>,
573 B extends ActionCreator<any>
574>(actionCreator: A, dispatch: Dispatch): B
575
576export function bindActionCreators<A, M extends ActionCreatorsMapObject<A>>(
577 actionCreators: M,
578 dispatch: Dispatch
579): M
580
581export function bindActionCreators<
582 M extends ActionCreatorsMapObject<any>,
583 N extends ActionCreatorsMapObject<any>
584>(actionCreators: M, dispatch: Dispatch): N
585
586/* compose */
587
588type Func0<R> = () => R
589type Func1<T1, R> = (a1: T1) => R
590type Func2<T1, T2, R> = (a1: T1, a2: T2) => R
591type Func3<T1, T2, T3, R> = (a1: T1, a2: T2, a3: T3, ...args: any[]) => R
592
593/**
594 * Composes single-argument functions from right to left. The rightmost
595 * function can take multiple arguments as it provides the signature for the
596 * resulting composite function.
597 *
598 * @param funcs The functions to compose.
599 * @returns R function obtained by composing the argument functions from right
600 * to left. For example, `compose(f, g, h)` is identical to doing
601 * `(...args) => f(g(h(...args)))`.
602 */
603export function compose(): <R>(a: R) => R
604
605export function compose<F extends Function>(f: F): F
606
607/* two functions */
608export function compose<A, R>(f1: (b: A) => R, f2: Func0<A>): Func0<R>
609export function compose<A, T1, R>(
610 f1: (b: A) => R,
611 f2: Func1<T1, A>
612): Func1<T1, R>
613export function compose<A, T1, T2, R>(
614 f1: (b: A) => R,
615 f2: Func2<T1, T2, A>
616): Func2<T1, T2, R>
617export function compose<A, T1, T2, T3, R>(
618 f1: (b: A) => R,
619 f2: Func3<T1, T2, T3, A>
620): Func3<T1, T2, T3, R>
621
622/* three functions */
623export function compose<A, B, R>(
624 f1: (b: B) => R,
625 f2: (a: A) => B,
626 f3: Func0<A>
627): Func0<R>
628export function compose<A, B, T1, R>(
629 f1: (b: B) => R,
630 f2: (a: A) => B,
631 f3: Func1<T1, A>
632): Func1<T1, R>
633export function compose<A, B, T1, T2, R>(
634 f1: (b: B) => R,
635 f2: (a: A) => B,
636 f3: Func2<T1, T2, A>
637): Func2<T1, T2, R>
638export function compose<A, B, T1, T2, T3, R>(
639 f1: (b: B) => R,
640 f2: (a: A) => B,
641 f3: Func3<T1, T2, T3, A>
642): Func3<T1, T2, T3, R>
643
644/* four functions */
645export function compose<A, B, C, R>(
646 f1: (b: C) => R,
647 f2: (a: B) => C,
648 f3: (a: A) => B,
649 f4: Func0<A>
650): Func0<R>
651export function compose<A, B, C, T1, R>(
652 f1: (b: C) => R,
653 f2: (a: B) => C,
654 f3: (a: A) => B,
655 f4: Func1<T1, A>
656): Func1<T1, R>
657export function compose<A, B, C, T1, T2, R>(
658 f1: (b: C) => R,
659 f2: (a: B) => C,
660 f3: (a: A) => B,
661 f4: Func2<T1, T2, A>
662): Func2<T1, T2, R>
663export function compose<A, B, C, T1, T2, T3, R>(
664 f1: (b: C) => R,
665 f2: (a: B) => C,
666 f3: (a: A) => B,
667 f4: Func3<T1, T2, T3, A>
668): Func3<T1, T2, T3, R>
669
670/* rest */
671export function compose<R>(
672 f1: (b: any) => R,
673 ...funcs: Function[]
674): (...args: any[]) => R
675
676export function compose<R>(...funcs: Function[]): (...args: any[]) => R
677
\No newline at end of file