Debian Codegraph @

install/freeipa-webui/node_modules/@reduxjs/toolkit/dist/index.d.ts

raw
1 import { ActionCreator, Action, Middleware, StoreEnhancer, UnknownAction, Reducer, ReducersMapObject, Store, StateFromReducersMapObject, Dispatch, MiddlewareAPI } from 'redux';
2 export * from 'redux';
3 import { Draft } from 'immer';
4 export { Draft, produce as createNextState, current, freeze, isDraft, original } from 'immer';
5 import * as reselect from 'reselect';
6 import { createSelectorCreator, weakMapMemoize, Selector, CreateSelectorFunction } from 'reselect';
7 export { OutputSelector, Selector, createSelector, createSelectorCreator, lruMemoize, weakMapMemoize } from 'reselect';
8 import { ThunkMiddleware, ThunkDispatch } from 'redux-thunk';
9 export { ThunkAction, ThunkDispatch, ThunkMiddleware } from 'redux-thunk';
10 import { UncheckedIndexedAccess } from './uncheckedindexed.js';
11
12 declare const createDraftSafeSelectorCreator: typeof createSelectorCreator;
13 /**
14 * "Draft-Safe" version of `reselect`'s `createSelector`:
15 * If an `immer`-drafted object is passed into the resulting selector's first argument,
16 * the selector will act on the current draft value, instead of returning a cached value
17 * that might be possibly outdated if the draft has been modified since.
18 * @public
19 */
20 declare const createDraftSafeSelector: reselect.CreateSelectorFunction<typeof weakMapMemoize, typeof weakMapMemoize, any>;
21
22 /**
23 * @public
24 */
25 interface DevToolsEnhancerOptions {
26 /**
27 * the instance name to be showed on the monitor page. Default value is `document.title`.
28 * If not specified and there's no document title, it will consist of `tabId` and `instanceId`.
29 */
30 name?: string;
31 /**
32 * action creators functions to be available in the Dispatcher.
33 */
34 actionCreators?: ActionCreator<any>[] | {
35 [key: string]: ActionCreator<any>;
36 };
37 /**
38 * if more than one action is dispatched in the indicated interval, all new actions will be collected and sent at once.
39 * It is the joint between performance and speed. When set to `0`, all actions will be sent instantly.
40 * Set it to a higher value when experiencing perf issues (also `maxAge` to a lower value).
41 *
42 * @default 500 ms.
43 */
44 latency?: number;
45 /**
46 * (> 1) - maximum allowed actions to be stored in the history tree. The oldest actions are removed once maxAge is reached. It's critical for performance.
47 *
48 * @default 50
49 */
50 maxAge?: number;
51 /**
52 * Customizes how actions and state are serialized and deserialized. Can be a boolean or object. If given a boolean, the behavior is the same as if you
53 * were to pass an object and specify `options` as a boolean. Giving an object allows fine-grained customization using the `replacer` and `reviver`
54 * functions.
55 */
56 serialize?: boolean | {
57 /**
58 * - `undefined` - will use regular `JSON.stringify` to send data (it's the fast mode).
59 * - `false` - will handle also circular references.
60 * - `true` - will handle also date, regex, undefined, error objects, symbols, maps, sets and functions.
61 * - object, which contains `date`, `regex`, `undefined`, `error`, `symbol`, `map`, `set` and `function` keys.
62 * For each of them you can indicate if to include (by setting as `true`).
63 * For `function` key you can also specify a custom function which handles serialization.
64 * See [`jsan`](https://github.com/kolodny/jsan) for more details.
65 */
66 options?: undefined | boolean | {
67 date?: true;
68 regex?: true;
69 undefined?: true;
70 error?: true;
71 symbol?: true;
72 map?: true;
73 set?: true;
74 function?: true | ((fn: (...args: any[]) => any) => string);
75 };
76 /**
77 * [JSON replacer function](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The_replacer_parameter) used for both actions and states stringify.
78 * In addition, you can specify a data type by adding a [`__serializedType__`](https://github.com/zalmoxisus/remotedev-serialize/blob/master/helpers/index.js#L4)
79 * key. So you can deserialize it back while importing or persisting data.
80 * Moreover, it will also [show a nice preview showing the provided custom type](https://cloud.githubusercontent.com/assets/7957859/21814330/a17d556a-d761-11e6-85ef-159dd12f36c5.png):
81 */
82 replacer?: (key: string, value: unknown) => any;
83 /**
84 * [JSON `reviver` function](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Using_the_reviver_parameter)
85 * used for parsing the imported actions and states. See [`remotedev-serialize`](https://github.com/zalmoxisus/remotedev-serialize/blob/master/immutable/serialize.js#L8-L41)
86 * as an example on how to serialize special data types and get them back.
87 */
88 reviver?: (key: string, value: unknown) => any;
89 /**
90 * Automatically serialize/deserialize immutablejs via [remotedev-serialize](https://github.com/zalmoxisus/remotedev-serialize).
91 * Just pass the Immutable library. It will support all ImmutableJS structures. You can even export them into a file and get them back.
92 * The only exception is `Record` class, for which you should pass this in addition the references to your classes in `refs`.
93 */
94 immutable?: any;
95 /**
96 * ImmutableJS `Record` classes used to make possible restore its instances back when importing, persisting...
97 */
98 refs?: any;
99 };
100 /**
101 * function which takes `action` object and id number as arguments, and should return `action` object back.
102 */
103 actionSanitizer?: <A extends Action>(action: A, id: number) => A;
104 /**
105 * function which takes `state` object and index as arguments, and should return `state` object back.
106 */
107 stateSanitizer?: <S>(state: S, index: number) => S;
108 /**
109 * *string or array of strings as regex* - actions types to be hidden / shown in the monitors (while passed to the reducers).
110 * If `actionsAllowlist` specified, `actionsDenylist` is ignored.
111 */
112 actionsDenylist?: string | string[];
113 /**
114 * *string or array of strings as regex* - actions types to be hidden / shown in the monitors (while passed to the reducers).
115 * If `actionsAllowlist` specified, `actionsDenylist` is ignored.
116 */
117 actionsAllowlist?: string | string[];
118 /**
119 * called for every action before sending, takes `state` and `action` object, and returns `true` in case it allows sending the current data to the monitor.
120 * Use it as a more advanced version of `actionsDenylist`/`actionsAllowlist` parameters.
121 */
122 predicate?: <S, A extends Action>(state: S, action: A) => boolean;
123 /**
124 * if specified as `false`, it will not record the changes till clicking on `Start recording` button.
125 * Available only for Redux enhancer, for others use `autoPause`.
126 *
127 * @default true
128 */
129 shouldRecordChanges?: boolean;
130 /**
131 * if specified, whenever clicking on `Pause recording` button and there are actions in the history log, will add this action type.
132 * If not specified, will commit when paused. Available only for Redux enhancer.
133 *
134 * @default "@@PAUSED""
135 */
136 pauseActionType?: string;
137 /**
138 * auto pauses when the extension’s window is not opened, and so has zero impact on your app when not in use.
139 * Not available for Redux enhancer (as it already does it but storing the data to be sent).
140 *
141 * @default false
142 */
143 autoPause?: boolean;
144 /**
145 * if specified as `true`, it will not allow any non-monitor actions to be dispatched till clicking on `Unlock changes` button.
146 * Available only for Redux enhancer.
147 *
148 * @default false
149 */
150 shouldStartLocked?: boolean;
151 /**
152 * if set to `false`, will not recompute the states on hot reloading (or on replacing the reducers). Available only for Redux enhancer.
153 *
154 * @default true
155 */
156 shouldHotReload?: boolean;
157 /**
158 * if specified as `true`, whenever there's an exception in reducers, the monitors will show the error message, and next actions will not be dispatched.
159 *
160 * @default false
161 */
162 shouldCatchErrors?: boolean;
163 /**
164 * If you want to restrict the extension, specify the features you allow.
165 * If not specified, all of the features are enabled. When set as an object, only those included as `true` will be allowed.
166 * Note that except `true`/`false`, `import` and `export` can be set as `custom` (which is by default for Redux enhancer), meaning that the importing/exporting occurs on the client side.
167 * Otherwise, you'll get/set the data right from the monitor part.
168 */
169 features?: {
170 /**
171 * start/pause recording of dispatched actions
172 */
173 pause?: boolean;
174 /**
175 * lock/unlock dispatching actions and side effects
176 */
177 lock?: boolean;
178 /**
179 * persist states on page reloading
180 */
181 persist?: boolean;
182 /**
183 * export history of actions in a file
184 */
185 export?: boolean | 'custom';
186 /**
187 * import history of actions from a file
188 */
189 import?: boolean | 'custom';
190 /**
191 * jump back and forth (time travelling)
192 */
193 jump?: boolean;
194 /**
195 * skip (cancel) actions
196 */
197 skip?: boolean;
198 /**
199 * drag and drop actions in the history list
200 */
201 reorder?: boolean;
202 /**
203 * dispatch custom actions or action creators
204 */
205 dispatch?: boolean;
206 /**
207 * generate tests for the selected actions
208 */
209 test?: boolean;
210 };
211 /**
212 * Set to true or a stacktrace-returning function to record call stack traces for dispatched actions.
213 * Defaults to false.
214 */
215 trace?: boolean | (<A extends Action>(action: A) => string);
216 /**
217 * The maximum number of stack trace entries to record per action. Defaults to 10.
218 */
219 traceLimit?: number;
220 }
221
222 interface ActionCreatorInvariantMiddlewareOptions {
223 /**
224 * The function to identify whether a value is an action creator.
225 * The default checks for a function with a static type property and match method.
226 */
227 isActionCreator?: (action: unknown) => action is Function & {
228 type?: unknown;
229 };
230 }
231 declare function createActionCreatorInvariantMiddleware(options?: ActionCreatorInvariantMiddlewareOptions): Middleware;
232
233 /**
234 * Returns true if the passed value is "plain", i.e. a value that is either
235 * directly JSON-serializable (boolean, number, string, array, plain object)
236 * or `undefined`.
237 *
238 * @param val The value to check.
239 *
240 * @public
241 */
242 declare function isPlain(val: any): boolean;
243 interface NonSerializableValue {
244 keyPath: string;
245 value: unknown;
246 }
247 type IgnorePaths = readonly (string | RegExp)[];
248 /**
249 * @public
250 */
251 declare function findNonSerializableValue(value: unknown, path?: string, isSerializable?: (value: unknown) => boolean, getEntries?: (value: unknown) => [string, any][], ignoredPaths?: IgnorePaths, cache?: WeakSet<object>): NonSerializableValue | false;
252 /**
253 * Options for `createSerializableStateInvariantMiddleware()`.
254 *
255 * @public
256 */
257 interface SerializableStateInvariantMiddlewareOptions {
258 /**
259 * The function to check if a value is considered serializable. This
260 * function is applied recursively to every value contained in the
261 * state. Defaults to `isPlain()`.
262 */
263 isSerializable?: (value: any) => boolean;
264 /**
265 * The function that will be used to retrieve entries from each
266 * value. If unspecified, `Object.entries` will be used. Defaults
267 * to `undefined`.
268 */
269 getEntries?: (value: any) => [string, any][];
270 /**
271 * An array of action types to ignore when checking for serializability.
272 * Defaults to []
273 */
274 ignoredActions?: string[];
275 /**
276 * An array of dot-separated path strings or regular expressions to ignore
277 * when checking for serializability, Defaults to
278 * ['meta.arg', 'meta.baseQueryMeta']
279 */
280 ignoredActionPaths?: (string | RegExp)[];
281 /**
282 * An array of dot-separated path strings or regular expressions to ignore
283 * when checking for serializability, Defaults to []
284 */
285 ignoredPaths?: (string | RegExp)[];
286 /**
287 * Execution time warning threshold. If the middleware takes longer
288 * than `warnAfter` ms, a warning will be displayed in the console.
289 * Defaults to 32ms.
290 */
291 warnAfter?: number;
292 /**
293 * Opt out of checking state. When set to `true`, other state-related params will be ignored.
294 */
295 ignoreState?: boolean;
296 /**
297 * Opt out of checking actions. When set to `true`, other action-related params will be ignored.
298 */
299 ignoreActions?: boolean;
300 /**
301 * Opt out of caching the results. The cache uses a WeakSet and speeds up repeated checking processes.
302 * The cache is automatically disabled if no browser support for WeakSet is present.
303 */
304 disableCache?: boolean;
305 }
306 /**
307 * Creates a middleware that, after every state change, checks if the new
308 * state is serializable. If a non-serializable value is found within the
309 * state, an error is printed to the console.
310 *
311 * @param options Middleware options.
312 *
313 * @public
314 */
315 declare function createSerializableStateInvariantMiddleware(options?: SerializableStateInvariantMiddlewareOptions): Middleware;
316
317 /**
318 * The default `isImmutable` function.
319 *
320 * @public
321 */
322 declare function isImmutableDefault(value: unknown): boolean;
323 type IsImmutableFunc = (value: any) => boolean;
324 /**
325 * Options for `createImmutableStateInvariantMiddleware()`.
326 *
327 * @public
328 */
329 interface ImmutableStateInvariantMiddlewareOptions {
330 /**
331 Callback function to check if a value is considered to be immutable.
332 This function is applied recursively to every value contained in the state.
333 The default implementation will return true for primitive types
334 (like numbers, strings, booleans, null and undefined).
335 */
336 isImmutable?: IsImmutableFunc;
337 /**
338 An array of dot-separated path strings that match named nodes from
339 the root state to ignore when checking for immutability.
340 Defaults to undefined
341 */
342 ignoredPaths?: IgnorePaths;
343 /** Print a warning if checks take longer than N ms. Default: 32ms */
344 warnAfter?: number;
345 }
346 /**
347 * Creates a middleware that checks whether any state was mutated in between
348 * dispatches or during a dispatch. If any mutations are detected, an error is
349 * thrown.
350 *
351 * @param options Middleware options.
352 *
353 * @public
354 */
355 declare function createImmutableStateInvariantMiddleware(options?: ImmutableStateInvariantMiddlewareOptions): Middleware;
356
357 declare class Tuple<Items extends ReadonlyArray<unknown> = []> extends Array<Items[number]> {
358 constructor(length: number);
359 constructor(...items: Items);
360 static get [Symbol.species](): any;
361 concat<AdditionalItems extends ReadonlyArray<unknown>>(items: Tuple<AdditionalItems>): Tuple<[...Items, ...AdditionalItems]>;
362 concat<AdditionalItems extends ReadonlyArray<unknown>>(items: AdditionalItems): Tuple<[...Items, ...AdditionalItems]>;
363 concat<AdditionalItems extends ReadonlyArray<unknown>>(...items: AdditionalItems): Tuple<[...Items, ...AdditionalItems]>;
364 prepend<AdditionalItems extends ReadonlyArray<unknown>>(items: Tuple<AdditionalItems>): Tuple<[...AdditionalItems, ...Items]>;
365 prepend<AdditionalItems extends ReadonlyArray<unknown>>(items: AdditionalItems): Tuple<[...AdditionalItems, ...Items]>;
366 prepend<AdditionalItems extends ReadonlyArray<unknown>>(...items: AdditionalItems): Tuple<[...AdditionalItems, ...Items]>;
367 }
368
369 /**
370 * return True if T is `any`, otherwise return False
371 * taken from https://github.com/joonhocho/tsdef
372 *
373 * @internal
374 */
375 type IsAny<T, True, False = never> = true | false extends (T extends never ? true : false) ? True : False;
376 type CastAny<T, CastTo> = IsAny<T, CastTo, T>;
377 /**
378 * return True if T is `unknown`, otherwise return False
379 * taken from https://github.com/joonhocho/tsdef
380 *
381 * @internal
382 */
383 type IsUnknown<T, True, False = never> = unknown extends T ? IsAny<T, False, True> : False;
384 type FallbackIfUnknown<T, Fallback> = IsUnknown<T, Fallback, T>;
385 /**
386 * @internal
387 */
388 type IfMaybeUndefined<P, True, False> = [undefined] extends [P] ? True : False;
389 /**
390 * @internal
391 */
392 type IfVoid<P, True, False> = [void] extends [P] ? True : False;
393 /**
394 * @internal
395 */
396 type IsEmptyObj<T, True, False = never> = T extends any ? keyof T extends never ? IsUnknown<T, False, IfMaybeUndefined<T, False, IfVoid<T, False, True>>> : False : never;
397 /**
398 * returns True if TS version is above 3.5, False if below.
399 * uses feature detection to detect TS version >= 3.5
400 * * versions below 3.5 will return `{}` for unresolvable interference
401 * * versions above will return `unknown`
402 *
403 * @internal
404 */
405 type AtLeastTS35<True, False> = [True, False][IsUnknown<ReturnType<(<T>() => T)>, 0, 1>];
406 /**
407 * @internal
408 */
409 type IsUnknownOrNonInferrable<T, True, False> = AtLeastTS35<IsUnknown<T, True, False>, IsEmptyObj<T, True, IsUnknown<T, True, False>>>;
410 /**
411 * Convert a Union type `(A|B)` to an intersection type `(A&B)`
412 */
413 type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (k: infer I) => void ? I : never;
414 type ExcludeFromTuple<T, E, Acc extends unknown[] = []> = T extends [
415 infer Head,
416 ...infer Tail
417 ] ? ExcludeFromTuple<Tail, E, [...Acc, ...([Head] extends [E] ? [] : [Head])]> : Acc;
418 type ExtractDispatchFromMiddlewareTuple<MiddlewareTuple extends readonly any[], Acc extends {}> = MiddlewareTuple extends [infer Head, ...infer Tail] ? ExtractDispatchFromMiddlewareTuple<Tail, Acc & (Head extends Middleware<infer D> ? IsAny<D, {}, D> : {})> : Acc;
419 type ExtractDispatchExtensions<M> = M extends Tuple<infer MiddlewareTuple> ? ExtractDispatchFromMiddlewareTuple<MiddlewareTuple, {}> : M extends ReadonlyArray<Middleware> ? ExtractDispatchFromMiddlewareTuple<[...M], {}> : never;
420 type ExtractStoreExtensionsFromEnhancerTuple<EnhancerTuple extends readonly any[], Acc extends {}> = EnhancerTuple extends [infer Head, ...infer Tail] ? ExtractStoreExtensionsFromEnhancerTuple<Tail, Acc & (Head extends StoreEnhancer<infer Ext> ? IsAny<Ext, {}, Ext> : {})> : Acc;
421 type ExtractStoreExtensions<E> = E extends Tuple<infer EnhancerTuple> ? ExtractStoreExtensionsFromEnhancerTuple<EnhancerTuple, {}> : E extends ReadonlyArray<StoreEnhancer> ? UnionToIntersection<E[number] extends StoreEnhancer<infer Ext> ? Ext extends {} ? IsAny<Ext, {}, Ext> : {} : {}> : never;
422 type ExtractStateExtensionsFromEnhancerTuple<EnhancerTuple extends readonly any[], Acc extends {}> = EnhancerTuple extends [infer Head, ...infer Tail] ? ExtractStateExtensionsFromEnhancerTuple<Tail, Acc & (Head extends StoreEnhancer<any, infer StateExt> ? IsAny<StateExt, {}, StateExt> : {})> : Acc;
423 type ExtractStateExtensions<E> = E extends Tuple<infer EnhancerTuple> ? ExtractStateExtensionsFromEnhancerTuple<EnhancerTuple, {}> : E extends ReadonlyArray<StoreEnhancer> ? UnionToIntersection<E[number] extends StoreEnhancer<any, infer StateExt> ? StateExt extends {} ? IsAny<StateExt, {}, StateExt> : {} : {}> : never;
424 /**
425 * Helper type. Passes T out again, but boxes it in a way that it cannot
426 * "widen" the type by accident if it is a generic that should be inferred
427 * from elsewhere.
428 *
429 * @internal
430 */
431 type NoInfer<T> = [T][T extends any ? 0 : never];
432 type NonUndefined<T> = T extends undefined ? never : T;
433 type WithRequiredProp<T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>;
434 type WithOptionalProp<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
435 interface TypeGuard<T> {
436 (value: any): value is T;
437 }
438 interface HasMatchFunction<T> {
439 match: TypeGuard<T>;
440 }
441 /** @public */
442 type Matcher<T> = HasMatchFunction<T> | TypeGuard<T>;
443 /** @public */
444 type ActionFromMatcher<M extends Matcher<any>> = M extends Matcher<infer T> ? T : never;
445 type Id<T> = {
446 [K in keyof T]: T[K];
447 } & {};
448 type Tail<T extends any[]> = T extends [any, ...infer Tail] ? Tail : never;
449 type UnknownIfNonSpecific<T> = {} extends T ? unknown : T;
450 /**
451 * A Promise that will never reject.
452 * @see https://github.com/reduxjs/redux-toolkit/issues/4101
453 */
454 type SafePromise<T> = Promise<T> & {
455 __linterBrands: 'SafePromise';
456 };
457
458 interface ThunkOptions<E = any> {
459 extraArgument: E;
460 }
461 interface GetDefaultMiddlewareOptions {
462 thunk?: boolean | ThunkOptions;
463 immutableCheck?: boolean | ImmutableStateInvariantMiddlewareOptions;
464 serializableCheck?: boolean | SerializableStateInvariantMiddlewareOptions;
465 actionCreatorCheck?: boolean | ActionCreatorInvariantMiddlewareOptions;
466 }
467 type ThunkMiddlewareFor<S, O extends GetDefaultMiddlewareOptions = {}> = O extends {
468 thunk: false;
469 } ? never : O extends {
470 thunk: {
471 extraArgument: infer E;
472 };
473 } ? ThunkMiddleware<S, UnknownAction, E> : ThunkMiddleware<S, UnknownAction>;
474 type GetDefaultMiddleware<S = any> = <O extends GetDefaultMiddlewareOptions = {
475 thunk: true;
476 immutableCheck: true;
477 serializableCheck: true;
478 actionCreatorCheck: true;
479 }>(options?: O) => Tuple<ExcludeFromTuple<[ThunkMiddlewareFor<S, O>], never>>;
480
481 declare const SHOULD_AUTOBATCH = "RTK_autoBatch";
482 declare const prepareAutoBatched: <T>() => (payload: T) => {
483 payload: T;
484 meta: unknown;
485 };
486 type AutoBatchOptions = {
487 type: 'tick';
488 } | {
489 type: 'timer';
490 timeout: number;
491 } | {
492 type: 'raf';
493 } | {
494 type: 'callback';
495 queueNotification: (notify: () => void) => void;
496 };
497 /**
498 * A Redux store enhancer that watches for "low-priority" actions, and delays
499 * notifying subscribers until either the queued callback executes or the
500 * next "standard-priority" action is dispatched.
501 *
502 * This allows dispatching multiple "low-priority" actions in a row with only
503 * a single subscriber notification to the UI after the sequence of actions
504 * is finished, thus improving UI re-render performance.
505 *
506 * Watches for actions with the `action.meta[SHOULD_AUTOBATCH]` attribute.
507 * This can be added to `action.meta` manually, or by using the
508 * `prepareAutoBatched` helper.
509 *
510 * By default, it will queue a notification for the end of the event loop tick.
511 * However, you can pass several other options to configure the behavior:
512 * - `{type: 'tick'}`: queues using `queueMicrotask`
513 * - `{type: 'timer', timeout: number}`: queues using `setTimeout`
514 * - `{type: 'raf'}`: queues using `requestAnimationFrame` (default)
515 * - `{type: 'callback', queueNotification: (notify: () => void) => void}`: lets you provide your own callback
516 *
517 *
518 */
519 declare const autoBatchEnhancer: (options?: AutoBatchOptions) => StoreEnhancer;
520
521 type GetDefaultEnhancersOptions = {
522 autoBatch?: boolean | AutoBatchOptions;
523 };
524 type GetDefaultEnhancers<M extends Middlewares<any>> = (options?: GetDefaultEnhancersOptions) => Tuple<[StoreEnhancer<{
525 dispatch: ExtractDispatchExtensions<M>;
526 }>]>;
527
528 /**
529 * Options for `configureStore()`.
530 *
531 * @public
532 */
533 interface ConfigureStoreOptions<S = any, A extends Action = UnknownAction, M extends Tuple<Middlewares<S>> = Tuple<Middlewares<S>>, E extends Tuple<Enhancers> = Tuple<Enhancers>, P = S> {
534 /**
535 * A single reducer function that will be used as the root reducer, or an
536 * object of slice reducers that will be passed to `combineReducers()`.
537 */
538 reducer: Reducer<S, A, P> | ReducersMapObject<S, A, P>;
539 /**
540 * An array of Redux middleware to install, or a callback receiving `getDefaultMiddleware` and returning a Tuple of middleware.
541 * If not supplied, defaults to the set of middleware returned by `getDefaultMiddleware()`.
542 *
543 * @example `middleware: (gDM) => gDM().concat(logger, apiMiddleware, yourCustomMiddleware)`
544 * @see https://redux-toolkit.js.org/api/getDefaultMiddleware#intended-usage
545 */
546 middleware?: (getDefaultMiddleware: GetDefaultMiddleware<S>) => M;
547 /**
548 * Whether to enable Redux DevTools integration. Defaults to `true`.
549 *
550 * Additional configuration can be done by passing Redux DevTools options
551 */
552 devTools?: boolean | DevToolsEnhancerOptions;
553 /**
554 * The initial state, same as Redux's createStore.
555 * You may optionally specify it to hydrate the state
556 * from the server in universal apps, or to restore a previously serialized
557 * user session. If you use `combineReducers()` to produce the root reducer
558 * function (either directly or indirectly by passing an object as `reducer`),
559 * this must be an object with the same shape as the reducer map keys.
560 */
561 preloadedState?: P;
562 /**
563 * The store enhancers to apply. See Redux's `createStore()`.
564 * All enhancers will be included before the DevTools Extension enhancer.
565 * If you need to customize the order of enhancers, supply a callback
566 * function that will receive a `getDefaultEnhancers` function that returns a Tuple,
567 * and should return a Tuple of enhancers (such as `getDefaultEnhancers().concat(offline)`).
568 * If you only need to add middleware, you can use the `middleware` parameter instead.
569 */
570 enhancers?: (getDefaultEnhancers: GetDefaultEnhancers<M>) => E;
571 }
572 type Middlewares<S> = ReadonlyArray<Middleware<{}, S>>;
573 type Enhancers = ReadonlyArray<StoreEnhancer>;
574 /**
575 * A Redux store returned by `configureStore()`. Supports dispatching
576 * side-effectful _thunks_ in addition to plain actions.
577 *
578 * @public
579 */
580 type EnhancedStore<S = any, A extends Action = UnknownAction, E extends Enhancers = Enhancers> = ExtractStoreExtensions<E> & Store<S, A, UnknownIfNonSpecific<ExtractStateExtensions<E>>>;
581 /**
582 * A friendly abstraction over the standard Redux `createStore()` function.
583 *
584 * @param options The store configuration.
585 * @returns A configured Redux store.
586 *
587 * @public
588 */
589 declare function configureStore<S = any, A extends Action = UnknownAction, M extends Tuple<Middlewares<S>> = Tuple<[ThunkMiddlewareFor<S>]>, E extends Tuple<Enhancers> = Tuple<[
590 StoreEnhancer<{
591 dispatch: ExtractDispatchExtensions<M>;
592 }>,
593 StoreEnhancer
594 ]>, P = S>(options: ConfigureStoreOptions<S, A, M, E, P>): EnhancedStore<S, A, E>;
595
596 /**
597 * An action with a string type and an associated payload. This is the
598 * type of action returned by `createAction()` action creators.
599 *
600 * @template P The type of the action's payload.
601 * @template T the type used for the action type.
602 * @template M The type of the action's meta (optional)
603 * @template E The type of the action's error (optional)
604 *
605 * @public
606 */
607 type PayloadAction<P = void, T extends string = string, M = never, E = never> = {
608 payload: P;
609 type: T;
610 } & ([M] extends [never] ? {} : {
611 meta: M;
612 }) & ([E] extends [never] ? {} : {
613 error: E;
614 });
615 /**
616 * A "prepare" method to be used as the second parameter of `createAction`.
617 * Takes any number of arguments and returns a Flux Standard Action without
618 * type (will be added later) that *must* contain a payload (might be undefined).
619 *
620 * @public
621 */
622 type PrepareAction<P> = ((...args: any[]) => {
623 payload: P;
624 }) | ((...args: any[]) => {
625 payload: P;
626 meta: any;
627 }) | ((...args: any[]) => {
628 payload: P;
629 error: any;
630 }) | ((...args: any[]) => {
631 payload: P;
632 meta: any;
633 error: any;
634 });
635 /**
636 * Internal version of `ActionCreatorWithPreparedPayload`. Not to be used externally.
637 *
638 * @internal
639 */
640 type _ActionCreatorWithPreparedPayload<PA extends PrepareAction<any> | void, T extends string = string> = PA extends PrepareAction<infer P> ? ActionCreatorWithPreparedPayload<Parameters<PA>, P, T, ReturnType<PA> extends {
641 error: infer E;
642 } ? E : never, ReturnType<PA> extends {
643 meta: infer M;
644 } ? M : never> : void;
645 /**
646 * Basic type for all action creators.
647 *
648 * @inheritdoc {redux#ActionCreator}
649 */
650 type BaseActionCreator<P, T extends string, M = never, E = never> = {
651 type: T;
652 match: (action: unknown) => action is PayloadAction<P, T, M, E>;
653 };
654 /**
655 * An action creator that takes multiple arguments that are passed
656 * to a `PrepareAction` method to create the final Action.
657 * @typeParam Args arguments for the action creator function
658 * @typeParam P `payload` type
659 * @typeParam T `type` name
660 * @typeParam E optional `error` type
661 * @typeParam M optional `meta` type
662 *
663 * @inheritdoc {redux#ActionCreator}
664 *
665 * @public
666 */
667 interface ActionCreatorWithPreparedPayload<Args extends unknown[], P, T extends string = string, E = never, M = never> extends BaseActionCreator<P, T, M, E> {
668 /**
669 * Calling this {@link redux#ActionCreator} with `Args` will return
670 * an Action with a payload of type `P` and (depending on the `PrepareAction`
671 * method used) a `meta`- and `error` property of types `M` and `E` respectively.
672 */
673 (...args: Args): PayloadAction<P, T, M, E>;
674 }
675 /**
676 * An action creator of type `T` that takes an optional payload of type `P`.
677 *
678 * @inheritdoc {redux#ActionCreator}
679 *
680 * @public
681 */
682 interface ActionCreatorWithOptionalPayload<P, T extends string = string> extends BaseActionCreator<P, T> {
683 /**
684 * Calling this {@link redux#ActionCreator} with an argument will
685 * return a {@link PayloadAction} of type `T` with a payload of `P`.
686 * Calling it without an argument will return a PayloadAction with a payload of `undefined`.
687 */
688 (payload?: P): PayloadAction<P, T>;
689 }
690 /**
691 * An action creator of type `T` that takes no payload.
692 *
693 * @inheritdoc {redux#ActionCreator}
694 *
695 * @public
696 */
697 interface ActionCreatorWithoutPayload<T extends string = string> extends BaseActionCreator<undefined, T> {
698 /**
699 * Calling this {@link redux#ActionCreator} will
700 * return a {@link PayloadAction} of type `T` with a payload of `undefined`
701 */
702 (noArgument: void): PayloadAction<undefined, T>;
703 }
704 /**
705 * An action creator of type `T` that requires a payload of type P.
706 *
707 * @inheritdoc {redux#ActionCreator}
708 *
709 * @public
710 */
711 interface ActionCreatorWithPayload<P, T extends string = string> extends BaseActionCreator<P, T> {
712 /**
713 * Calling this {@link redux#ActionCreator} with an argument will
714 * return a {@link PayloadAction} of type `T` with a payload of `P`
715 */
716 (payload: P): PayloadAction<P, T>;
717 }
718 /**
719 * An action creator of type `T` whose `payload` type could not be inferred. Accepts everything as `payload`.
720 *
721 * @inheritdoc {redux#ActionCreator}
722 *
723 * @public
724 */
725 interface ActionCreatorWithNonInferrablePayload<T extends string = string> extends BaseActionCreator<unknown, T> {
726 /**
727 * Calling this {@link redux#ActionCreator} with an argument will
728 * return a {@link PayloadAction} of type `T` with a payload
729 * of exactly the type of the argument.
730 */
731 <PT extends unknown>(payload: PT): PayloadAction<PT, T>;
732 }
733 /**
734 * An action creator that produces actions with a `payload` attribute.
735 *
736 * @typeParam P the `payload` type
737 * @typeParam T the `type` of the resulting action
738 * @typeParam PA if the resulting action is preprocessed by a `prepare` method, the signature of said method.
739 *
740 * @public
741 */
742 type PayloadActionCreator<P = void, T extends string = string, PA extends PrepareAction<P> | void = void> = IfPrepareActionMethodProvided<PA, _ActionCreatorWithPreparedPayload<PA, T>, IsAny<P, ActionCreatorWithPayload<any, T>, IsUnknownOrNonInferrable<P, ActionCreatorWithNonInferrablePayload<T>, IfVoid<P, ActionCreatorWithoutPayload<T>, IfMaybeUndefined<P, ActionCreatorWithOptionalPayload<P, T>, ActionCreatorWithPayload<P, T>>>>>>;
743 /**
744 * A utility function to create an action creator for the given action type
745 * string. The action creator accepts a single argument, which will be included
746 * in the action object as a field called payload. The action creator function
747 * will also have its toString() overridden so that it returns the action type.
748 *
749 * @param type The action type to use for created actions.
750 * @param prepare (optional) a method that takes any number of arguments and returns { payload } or { payload, meta }.
751 * If this is given, the resulting action creator will pass its arguments to this method to calculate payload & meta.
752 *
753 * @public
754 */
755 declare function createAction<P = void, T extends string = string>(type: T): PayloadActionCreator<P, T>;
756 /**
757 * A utility function to create an action creator for the given action type
758 * string. The action creator accepts a single argument, which will be included
759 * in the action object as a field called payload. The action creator function
760 * will also have its toString() overridden so that it returns the action type.
761 *
762 * @param type The action type to use for created actions.
763 * @param prepare (optional) a method that takes any number of arguments and returns { payload } or { payload, meta }.
764 * If this is given, the resulting action creator will pass its arguments to this method to calculate payload & meta.
765 *
766 * @public
767 */
768 declare function createAction<PA extends PrepareAction<any>, T extends string = string>(type: T, prepareAction: PA): PayloadActionCreator<ReturnType<PA>['payload'], T, PA>;
769 /**
770 * Returns true if value is an RTK-like action creator, with a static type property and match method.
771 */
772 declare function isActionCreator(action: unknown): action is BaseActionCreator<unknown, string> & Function;
773 /**
774 * Returns true if value is an action with a string type and valid Flux Standard Action keys.
775 */
776 declare function isFSA(action: unknown): action is {
777 type: string;
778 payload?: unknown;
779 error?: unknown;
780 meta?: unknown;
781 };
782 type IfPrepareActionMethodProvided<PA extends PrepareAction<any> | void, True, False> = PA extends (...args: any[]) => any ? True : False;
783
784 type TypedActionCreator<Type extends string> = {
785 (...args: any[]): Action<Type>;
786 type: Type;
787 };
788 /**
789 * A builder for an action <-> reducer map.
790 *
791 * @public
792 */
793 interface ActionReducerMapBuilder<State> {
794 /**
795 * Adds a case reducer to handle a single exact action type.
796 * @remarks
797 * All calls to `builder.addCase` must come before any calls to `builder.addMatcher` or `builder.addDefaultCase`.
798 * @param actionCreator - Either a plain action type string, or an action creator generated by [`createAction`](./createAction) that can be used to determine the action type.
799 * @param reducer - The actual case reducer function.
800 */
801 addCase<ActionCreator extends TypedActionCreator<string>>(actionCreator: ActionCreator, reducer: CaseReducer<State, ReturnType<ActionCreator>>): ActionReducerMapBuilder<State>;
802 /**
803 * Adds a case reducer to handle a single exact action type.
804 * @remarks
805 * All calls to `builder.addCase` must come before any calls to `builder.addMatcher` or `builder.addDefaultCase`.
806 * @param actionCreator - Either a plain action type string, or an action creator generated by [`createAction`](./createAction) that can be used to determine the action type.
807 * @param reducer - The actual case reducer function.
808 */
809 addCase<Type extends string, A extends Action<Type>>(type: Type, reducer: CaseReducer<State, A>): ActionReducerMapBuilder<State>;
810 /**
811 * Allows you to match your incoming actions against your own filter function instead of only the `action.type` property.
812 * @remarks
813 * If multiple matcher reducers match, all of them will be executed in the order
814 * they were defined in - even if a case reducer already matched.
815 * All calls to `builder.addMatcher` must come after any calls to `builder.addCase` and before any calls to `builder.addDefaultCase`.
816 * @param matcher - A matcher function. In TypeScript, this should be a [type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates)
817 * function
818 * @param reducer - The actual case reducer function.
819 *
820 * @example
821 ```ts
822 import {
823 createAction,
824 createReducer,
825 AsyncThunk,
826 UnknownAction,
827 } from "@reduxjs/toolkit";
828
829 type GenericAsyncThunk = AsyncThunk<unknown, unknown, any>;
830
831 type PendingAction = ReturnType<GenericAsyncThunk["pending"]>;
832 type RejectedAction = ReturnType<GenericAsyncThunk["rejected"]>;
833 type FulfilledAction = ReturnType<GenericAsyncThunk["fulfilled"]>;
834
835 const initialState: Record<string, string> = {};
836 const resetAction = createAction("reset-tracked-loading-state");
837
838 function isPendingAction(action: UnknownAction): action is PendingAction {
839 return typeof action.type === "string" && action.type.endsWith("/pending");
840 }
841
842 const reducer = createReducer(initialState, (builder) => {
843 builder
844 .addCase(resetAction, () => initialState)
845 // matcher can be defined outside as a type predicate function
846 .addMatcher(isPendingAction, (state, action) => {
847 state[action.meta.requestId] = "pending";
848 })
849 .addMatcher(
850 // matcher can be defined inline as a type predicate function
851 (action): action is RejectedAction => action.type.endsWith("/rejected"),
852 (state, action) => {
853 state[action.meta.requestId] = "rejected";
854 }
855 )
856 // matcher can just return boolean and the matcher can receive a generic argument
857 .addMatcher<FulfilledAction>(
858 (action) => action.type.endsWith("/fulfilled"),
859 (state, action) => {
860 state[action.meta.requestId] = "fulfilled";
861 }
862 );
863 });
864 ```
865 */
866 addMatcher<A>(matcher: TypeGuard<A> | ((action: any) => boolean), reducer: CaseReducer<State, A extends Action ? A : A & Action>): Omit<ActionReducerMapBuilder<State>, 'addCase'>;
867 /**
868 * Adds a "default case" reducer that is executed if no case reducer and no matcher
869 * reducer was executed for this action.
870 * @param reducer - The fallback "default case" reducer function.
871 *
872 * @example
873 ```ts
874 import { createReducer } from '@reduxjs/toolkit'
875 const initialState = { otherActions: 0 }
876 const reducer = createReducer(initialState, builder => {
877 builder
878 // .addCase(...)
879 // .addMatcher(...)
880 .addDefaultCase((state, action) => {
881 state.otherActions++
882 })
883 })
884 ```
885 */
886 addDefaultCase(reducer: CaseReducer<State, Action>): {};
887 }
888
889 /**
890 * Defines a mapping from action types to corresponding action object shapes.
891 *
892 * @deprecated This should not be used manually - it is only used for internal
893 * inference purposes and should not have any further value.
894 * It might be removed in the future.
895 * @public
896 */
897 type Actions<T extends keyof any = string> = Record<T, Action>;
898 /**
899 * A *case reducer* is a reducer function for a specific action type. Case
900 * reducers can be composed to full reducers using `createReducer()`.
901 *
902 * Unlike a normal Redux reducer, a case reducer is never called with an
903 * `undefined` state to determine the initial state. Instead, the initial
904 * state is explicitly specified as an argument to `createReducer()`.
905 *
906 * In addition, a case reducer can choose to mutate the passed-in `state`
907 * value directly instead of returning a new state. This does not actually
908 * cause the store state to be mutated directly; instead, thanks to
909 * [immer](https://github.com/mweststrate/immer), the mutations are
910 * translated to copy operations that result in a new state.
911 *
912 * @public
913 */
914 type CaseReducer<S = any, A extends Action = UnknownAction> = (state: Draft<S>, action: A) => NoInfer<S> | void | Draft<NoInfer<S>>;
915 /**
916 * A mapping from action types to case reducers for `createReducer()`.
917 *
918 * @deprecated This should not be used manually - it is only used
919 * for internal inference purposes and using it manually
920 * would lead to type erasure.
921 * It might be removed in the future.
922 * @public
923 */
924 type CaseReducers<S, AS extends Actions> = {
925 [T in keyof AS]: AS[T] extends Action ? CaseReducer<S, AS[T]> : void;
926 };
927 type NotFunction<T> = T extends Function ? never : T;
928 type ReducerWithInitialState<S extends NotFunction<any>> = Reducer<S> & {
929 getInitialState: () => S;
930 };
931 /**
932 * A utility function that allows defining a reducer as a mapping from action
933 * type to *case reducer* functions that handle these action types. The
934 * reducer's initial state is passed as the first argument.
935 *
936 * @remarks
937 * The body of every case reducer is implicitly wrapped with a call to
938 * `produce()` from the [immer](https://github.com/mweststrate/immer) library.
939 * This means that rather than returning a new state object, you can also
940 * mutate the passed-in state object directly; these mutations will then be
941 * automatically and efficiently translated into copies, giving you both
942 * convenience and immutability.
943 *
944 * @overloadSummary
945 * This function accepts a callback that receives a `builder` object as its argument.
946 * That builder provides `addCase`, `addMatcher` and `addDefaultCase` functions that may be
947 * called to define what actions this reducer will handle.
948 *
949 * @param initialState - `State | (() => State)`: The initial state that should be used when the reducer is called the first time. This may also be a "lazy initializer" function, which should return an initial state value when called. This will be used whenever the reducer is called with `undefined` as its state value, and is primarily useful for cases like reading initial state from `localStorage`.
950 * @param builderCallback - `(builder: Builder) => void` A callback that receives a *builder* object to define
951 * case reducers via calls to `builder.addCase(actionCreatorOrType, reducer)`.
952 * @example
953 ```ts
954 import {
955 createAction,
956 createReducer,
957 UnknownAction,
958 PayloadAction,
959 } from "@reduxjs/toolkit";
960
961 const increment = createAction<number>("increment");
962 const decrement = createAction<number>("decrement");
963
964 function isActionWithNumberPayload(
965 action: UnknownAction
966 ): action is PayloadAction<number> {
967 return typeof action.payload === "number";
968 }
969
970 const reducer = createReducer(
971 {
972 counter: 0,
973 sumOfNumberPayloads: 0,
974 unhandledActions: 0,
975 },
976 (builder) => {
977 builder
978 .addCase(increment, (state, action) => {
979 // action is inferred correctly here
980 state.counter += action.payload;
981 })
982 // You can chain calls, or have separate `builder.addCase()` lines each time
983 .addCase(decrement, (state, action) => {
984 state.counter -= action.payload;
985 })
986 // You can apply a "matcher function" to incoming actions
987 .addMatcher(isActionWithNumberPayload, (state, action) => {})
988 // and provide a default case if no other handlers matched
989 .addDefaultCase((state, action) => {});
990 }
991 );
992 ```
993 * @public
994 */
995 declare function createReducer<S extends NotFunction<any>>(initialState: S | (() => S), mapOrBuilderCallback: (builder: ActionReducerMapBuilder<S>) => void): ReducerWithInitialState<S>;
996
997 type SliceLike<ReducerPath extends string, State> = {
998 reducerPath: ReducerPath;
999 reducer: Reducer<State>;
1000 };
1001 type AnySliceLike = SliceLike<string, any>;
1002 type SliceLikeReducerPath<A extends AnySliceLike> = A extends SliceLike<infer ReducerPath, any> ? ReducerPath : never;
1003 type SliceLikeState<A extends AnySliceLike> = A extends SliceLike<any, infer State> ? State : never;
1004 type WithSlice<A extends AnySliceLike> = {
1005 [Path in SliceLikeReducerPath<A>]: SliceLikeState<A>;
1006 };
1007 type ReducerMap = Record<string, Reducer>;
1008 type ExistingSliceLike<DeclaredState> = {
1009 [ReducerPath in keyof DeclaredState]: SliceLike<ReducerPath & string, NonUndefined<DeclaredState[ReducerPath]>>;
1010 }[keyof DeclaredState];
1011 type InjectConfig = {
1012 /**
1013 * Allow replacing reducer with a different reference. Normally, an error will be thrown if a different reducer instance to the one already injected is used.
1014 */
1015 overrideExisting?: boolean;
1016 };
1017 /**
1018 * A reducer that allows for slices/reducers to be injected after initialisation.
1019 */
1020 interface CombinedSliceReducer<InitialState, DeclaredState = InitialState> extends Reducer<DeclaredState, UnknownAction, Partial<DeclaredState>> {
1021 /**
1022 * Provide a type for slices that will be injected lazily.
1023 *
1024 * One way to do this would be with interface merging:
1025 * ```ts
1026 *
1027 * export interface LazyLoadedSlices {}
1028 *
1029 * export const rootReducer = combineSlices(stringSlice).withLazyLoadedSlices<LazyLoadedSlices>();
1030 *
1031 * // elsewhere
1032 *
1033 * declare module './reducer' {
1034 * export interface LazyLoadedSlices extends WithSlice<typeof booleanSlice> {}
1035 * }
1036 *
1037 * const withBoolean = rootReducer.inject(booleanSlice);
1038 *
1039 * // elsewhere again
1040 *
1041 * declare module './reducer' {
1042 * export interface LazyLoadedSlices {
1043 * customName: CustomState
1044 * }
1045 * }
1046 *
1047 * const withCustom = rootReducer.inject({ reducerPath: "customName", reducer: customSlice.reducer })
1048 * ```
1049 */
1050 withLazyLoadedSlices<Lazy = {}>(): CombinedSliceReducer<InitialState, Id<DeclaredState & Partial<Lazy>>>;
1051 /**
1052 * Inject a slice.
1053 *
1054 * Accepts an individual slice, RTKQ API instance, or a "slice-like" { reducerPath, reducer } object.
1055 *
1056 * ```ts
1057 * rootReducer.inject(booleanSlice)
1058 * rootReducer.inject(baseApi)
1059 * rootReducer.inject({ reducerPath: 'boolean' as const, reducer: newReducer }, { overrideExisting: true })
1060 * ```
1061 *
1062 */
1063 inject<Sl extends Id<ExistingSliceLike<DeclaredState>>>(slice: Sl, config?: InjectConfig): CombinedSliceReducer<InitialState, Id<DeclaredState & WithSlice<Sl>>>;
1064 /**
1065 * Inject a slice.
1066 *
1067 * Accepts an individual slice, RTKQ API instance, or a "slice-like" { reducerPath, reducer } object.
1068 *
1069 * ```ts
1070 * rootReducer.inject(booleanSlice)
1071 * rootReducer.inject(baseApi)
1072 * rootReducer.inject({ reducerPath: 'boolean' as const, reducer: newReducer }, { overrideExisting: true })
1073 * ```
1074 *
1075 */
1076 inject<ReducerPath extends string, State>(slice: SliceLike<ReducerPath, State & (ReducerPath extends keyof DeclaredState ? never : State)>, config?: InjectConfig): CombinedSliceReducer<InitialState, Id<DeclaredState & WithSlice<SliceLike<ReducerPath, State>>>>;
1077 /**
1078 * Create a selector that guarantees that the slices injected will have a defined value when selector is run.
1079 *
1080 * ```ts
1081 * const selectBooleanWithoutInjection = (state: RootState) => state.boolean;
1082 * // ^? boolean | undefined
1083 *
1084 * const selectBoolean = rootReducer.inject(booleanSlice).selector((state) => {
1085 * // if action hasn't been dispatched since slice was injected, this would usually be undefined
1086 * // however selector() uses a Proxy around the first parameter to ensure that it evaluates to the initial state instead, if undefined
1087 * return state.boolean;
1088 * // ^? boolean
1089 * })
1090 * ```
1091 *
1092 * If the reducer is nested inside the root state, a selectState callback can be passed to retrieve the reducer's state.
1093 *
1094 * ```ts
1095 *
1096 * export interface LazyLoadedSlices {};
1097 *
1098 * export const innerReducer = combineSlices(stringSlice).withLazyLoadedSlices<LazyLoadedSlices>();
1099 *
1100 * export const rootReducer = combineSlices({ inner: innerReducer });
1101 *
1102 * export type RootState = ReturnType<typeof rootReducer>;
1103 *
1104 * // elsewhere
1105 *
1106 * declare module "./reducer.ts" {
1107 * export interface LazyLoadedSlices extends WithSlice<typeof booleanSlice> {}
1108 * }
1109 *
1110 * const withBool = innerReducer.inject(booleanSlice);
1111 *
1112 * const selectBoolean = withBool.selector(
1113 * (state) => state.boolean,
1114 * (rootState: RootState) => state.inner
1115 * );
1116 * // now expects to be passed RootState instead of innerReducer state
1117 *
1118 * ```
1119 *
1120 * Value passed to selectorFn will be a Proxy - use selector.original(proxy) to get original state value (useful for debugging)
1121 *
1122 * ```ts
1123 * const injectedReducer = rootReducer.inject(booleanSlice);
1124 * const selectBoolean = injectedReducer.selector((state) => {
1125 * console.log(injectedReducer.selector.original(state).boolean) // possibly undefined
1126 * return state.boolean
1127 * })
1128 * ```
1129 */
1130 selector: {
1131 /**
1132 * Create a selector that guarantees that the slices injected will have a defined value when selector is run.
1133 *
1134 * ```ts
1135 * const selectBooleanWithoutInjection = (state: RootState) => state.boolean;
1136 * // ^? boolean | undefined
1137 *
1138 * const selectBoolean = rootReducer.inject(booleanSlice).selector((state) => {
1139 * // if action hasn't been dispatched since slice was injected, this would usually be undefined
1140 * // however selector() uses a Proxy around the first parameter to ensure that it evaluates to the initial state instead, if undefined
1141 * return state.boolean;
1142 * // ^? boolean
1143 * })
1144 * ```
1145 *
1146 * Value passed to selectorFn will be a Proxy - use selector.original(proxy) to get original state value (useful for debugging)
1147 *
1148 * ```ts
1149 * const injectedReducer = rootReducer.inject(booleanSlice);
1150 * const selectBoolean = injectedReducer.selector((state) => {
1151 * console.log(injectedReducer.selector.original(state).boolean) // undefined
1152 * return state.boolean
1153 * })
1154 * ```
1155 */
1156 <Selector extends (state: DeclaredState, ...args: any[]) => unknown>(selectorFn: Selector): (state: WithOptionalProp<Parameters<Selector>[0], Exclude<keyof DeclaredState, keyof InitialState>>, ...args: Tail<Parameters<Selector>>) => ReturnType<Selector>;
1157 /**
1158 * Create a selector that guarantees that the slices injected will have a defined value when selector is run.
1159 *
1160 * ```ts
1161 * const selectBooleanWithoutInjection = (state: RootState) => state.boolean;
1162 * // ^? boolean | undefined
1163 *
1164 * const selectBoolean = rootReducer.inject(booleanSlice).selector((state) => {
1165 * // if action hasn't been dispatched since slice was injected, this would usually be undefined
1166 * // however selector() uses a Proxy around the first parameter to ensure that it evaluates to the initial state instead, if undefined
1167 * return state.boolean;
1168 * // ^? boolean
1169 * })
1170 * ```
1171 *
1172 * If the reducer is nested inside the root state, a selectState callback can be passed to retrieve the reducer's state.
1173 *
1174 * ```ts
1175 *
1176 * interface LazyLoadedSlices {};
1177 *
1178 * const innerReducer = combineSlices(stringSlice).withLazyLoadedSlices<LazyLoadedSlices>();
1179 *
1180 * const rootReducer = combineSlices({ inner: innerReducer });
1181 *
1182 * type RootState = ReturnType<typeof rootReducer>;
1183 *
1184 * // elsewhere
1185 *
1186 * declare module "./reducer.ts" {
1187 * interface LazyLoadedSlices extends WithSlice<typeof booleanSlice> {}
1188 * }
1189 *
1190 * const withBool = innerReducer.inject(booleanSlice);
1191 *
1192 * const selectBoolean = withBool.selector(
1193 * (state) => state.boolean,
1194 * (rootState: RootState) => state.inner
1195 * );
1196 * // now expects to be passed RootState instead of innerReducer state
1197 *
1198 * ```
1199 *
1200 * Value passed to selectorFn will be a Proxy - use selector.original(proxy) to get original state value (useful for debugging)
1201 *
1202 * ```ts
1203 * const injectedReducer = rootReducer.inject(booleanSlice);
1204 * const selectBoolean = injectedReducer.selector((state) => {
1205 * console.log(injectedReducer.selector.original(state).boolean) // possibly undefined
1206 * return state.boolean
1207 * })
1208 * ```
1209 */
1210 <Selector extends (state: DeclaredState, ...args: any[]) => unknown, RootState>(selectorFn: Selector, selectState: (rootState: RootState, ...args: Tail<Parameters<Selector>>) => WithOptionalProp<Parameters<Selector>[0], Exclude<keyof DeclaredState, keyof InitialState>>): (state: RootState, ...args: Tail<Parameters<Selector>>) => ReturnType<Selector>;
1211 /**
1212 * Returns the unproxied state. Useful for debugging.
1213 * @param state state Proxy, that ensures injected reducers have value
1214 * @returns original, unproxied state
1215 * @throws if value passed is not a state Proxy
1216 */
1217 original: (state: DeclaredState) => InitialState & Partial<DeclaredState>;
1218 };
1219 }
1220 type InitialState<Slices extends Array<AnySliceLike | ReducerMap>> = UnionToIntersection<Slices[number] extends infer Slice ? Slice extends AnySliceLike ? WithSlice<Slice> : StateFromReducersMapObject<Slice> : never>;
1221 declare function combineSlices<Slices extends Array<AnySliceLike | ReducerMap>>(...slices: Slices): CombinedSliceReducer<Id<InitialState<Slices>>>;
1222
1223 type BaseThunkAPI<S, E, D extends Dispatch = Dispatch, RejectedValue = unknown, RejectedMeta = unknown, FulfilledMeta = unknown> = {
1224 dispatch: D;
1225 getState: () => S;
1226 extra: E;
1227 requestId: string;
1228 signal: AbortSignal;
1229 abort: (reason?: string) => void;
1230 rejectWithValue: IsUnknown<RejectedMeta, (value: RejectedValue) => RejectWithValue<RejectedValue, RejectedMeta>, (value: RejectedValue, meta: RejectedMeta) => RejectWithValue<RejectedValue, RejectedMeta>>;
1231 fulfillWithValue: IsUnknown<FulfilledMeta, <FulfilledValue>(value: FulfilledValue) => FulfilledValue, <FulfilledValue>(value: FulfilledValue, meta: FulfilledMeta) => FulfillWithMeta<FulfilledValue, FulfilledMeta>>;
1232 };
1233 /**
1234 * @public
1235 */
1236 interface SerializedError {
1237 name?: string;
1238 message?: string;
1239 stack?: string;
1240 code?: string;
1241 }
1242 declare class RejectWithValue<Payload, RejectedMeta> {
1243 readonly payload: Payload;
1244 readonly meta: RejectedMeta;
1245 private readonly _type;
1246 constructor(payload: Payload, meta: RejectedMeta);
1247 }
1248 declare class FulfillWithMeta<Payload, FulfilledMeta> {
1249 readonly payload: Payload;
1250 readonly meta: FulfilledMeta;
1251 private readonly _type;
1252 constructor(payload: Payload, meta: FulfilledMeta);
1253 }
1254 /**
1255 * Serializes an error into a plain object.
1256 * Reworked from https://github.com/sindresorhus/serialize-error
1257 *
1258 * @public
1259 */
1260 declare const miniSerializeError: (value: any) => SerializedError;
1261 type AsyncThunkConfig = {
1262 state?: unknown;
1263 dispatch?: ThunkDispatch<unknown, unknown, UnknownAction>;
1264 extra?: unknown;
1265 rejectValue?: unknown;
1266 serializedErrorType?: unknown;
1267 pendingMeta?: unknown;
1268 fulfilledMeta?: unknown;
1269 rejectedMeta?: unknown;
1270 };
1271 type GetState<ThunkApiConfig> = ThunkApiConfig extends {
1272 state: infer State;
1273 } ? State : unknown;
1274 type GetExtra<ThunkApiConfig> = ThunkApiConfig extends {
1275 extra: infer Extra;
1276 } ? Extra : unknown;
1277 type GetDispatch<ThunkApiConfig> = ThunkApiConfig extends {
1278 dispatch: infer Dispatch;
1279 } ? FallbackIfUnknown<Dispatch, ThunkDispatch<GetState<ThunkApiConfig>, GetExtra<ThunkApiConfig>, UnknownAction>> : ThunkDispatch<GetState<ThunkApiConfig>, GetExtra<ThunkApiConfig>, UnknownAction>;
1280 type GetThunkAPI<ThunkApiConfig> = BaseThunkAPI<GetState<ThunkApiConfig>, GetExtra<ThunkApiConfig>, GetDispatch<ThunkApiConfig>, GetRejectValue<ThunkApiConfig>, GetRejectedMeta<ThunkApiConfig>, GetFulfilledMeta<ThunkApiConfig>>;
1281 type GetRejectValue<ThunkApiConfig> = ThunkApiConfig extends {
1282 rejectValue: infer RejectValue;
1283 } ? RejectValue : unknown;
1284 type GetPendingMeta<ThunkApiConfig> = ThunkApiConfig extends {
1285 pendingMeta: infer PendingMeta;
1286 } ? PendingMeta : unknown;
1287 type GetFulfilledMeta<ThunkApiConfig> = ThunkApiConfig extends {
1288 fulfilledMeta: infer FulfilledMeta;
1289 } ? FulfilledMeta : unknown;
1290 type GetRejectedMeta<ThunkApiConfig> = ThunkApiConfig extends {
1291 rejectedMeta: infer RejectedMeta;
1292 } ? RejectedMeta : unknown;
1293 type GetSerializedErrorType<ThunkApiConfig> = ThunkApiConfig extends {
1294 serializedErrorType: infer GetSerializedErrorType;
1295 } ? GetSerializedErrorType : SerializedError;
1296 type MaybePromise<T> = T | Promise<T> | (T extends any ? Promise<T> : never);
1297 /**
1298 * A type describing the return value of the `payloadCreator` argument to `createAsyncThunk`.
1299 * Might be useful for wrapping `createAsyncThunk` in custom abstractions.
1300 *
1301 * @public
1302 */
1303 type AsyncThunkPayloadCreatorReturnValue<Returned, ThunkApiConfig extends AsyncThunkConfig> = MaybePromise<IsUnknown<GetFulfilledMeta<ThunkApiConfig>, Returned, FulfillWithMeta<Returned, GetFulfilledMeta<ThunkApiConfig>>> | RejectWithValue<GetRejectValue<ThunkApiConfig>, GetRejectedMeta<ThunkApiConfig>>>;
1304 /**
1305 * A type describing the `payloadCreator` argument to `createAsyncThunk`.
1306 * Might be useful for wrapping `createAsyncThunk` in custom abstractions.
1307 *
1308 * @public
1309 */
1310 type AsyncThunkPayloadCreator<Returned, ThunkArg = void, ThunkApiConfig extends AsyncThunkConfig = {}> = (arg: ThunkArg, thunkAPI: GetThunkAPI<ThunkApiConfig>) => AsyncThunkPayloadCreatorReturnValue<Returned, ThunkApiConfig>;
1311 /**
1312 * A ThunkAction created by `createAsyncThunk`.
1313 * Dispatching it returns a Promise for either a
1314 * fulfilled or rejected action.
1315 * Also, the returned value contains an `abort()` method
1316 * that allows the asyncAction to be cancelled from the outside.
1317 *
1318 * @public
1319 */
1320 type AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig extends AsyncThunkConfig> = (dispatch: NonNullable<GetDispatch<ThunkApiConfig>>, getState: () => GetState<ThunkApiConfig>, extra: GetExtra<ThunkApiConfig>) => SafePromise<ReturnType<AsyncThunkFulfilledActionCreator<Returned, ThunkArg>> | ReturnType<AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig>>> & {
1321 abort: (reason?: string) => void;
1322 requestId: string;
1323 arg: ThunkArg;
1324 unwrap: () => Promise<Returned>;
1325 };
1326 /**
1327 * Config provided when calling the async thunk action creator.
1328 */
1329 interface AsyncThunkDispatchConfig {
1330 /**
1331 * An external `AbortSignal` that will be tracked by the internal `AbortSignal`.
1332 */
1333 signal?: AbortSignal;
1334 }
1335 type AsyncThunkActionCreator<Returned, ThunkArg, ThunkApiConfig extends AsyncThunkConfig> = IsAny<ThunkArg, (arg: ThunkArg, config?: AsyncThunkDispatchConfig) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig>, unknown extends ThunkArg ? (arg: ThunkArg, config?: AsyncThunkDispatchConfig) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig> : [ThunkArg] extends [void] | [undefined] ? (arg?: undefined, config?: AsyncThunkDispatchConfig) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig> : [void] extends [ThunkArg] ? (arg?: ThunkArg, config?: AsyncThunkDispatchConfig) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig> : [undefined] extends [ThunkArg] ? WithStrictNullChecks<(arg?: ThunkArg, config?: AsyncThunkDispatchConfig) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig>, (arg: ThunkArg, config?: AsyncThunkDispatchConfig) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig>> : (arg: ThunkArg, config?: AsyncThunkDispatchConfig) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig>>;
1336 /**
1337 * Options object for `createAsyncThunk`.
1338 *
1339 * @public
1340 */
1341 type AsyncThunkOptions<ThunkArg = void, ThunkApiConfig extends AsyncThunkConfig = {}> = {
1342 /**
1343 * A method to control whether the asyncThunk should be executed. Has access to the
1344 * `arg`, `api.getState()` and `api.extra` arguments.
1345 *
1346 * @returns `false` if it should be skipped
1347 */
1348 condition?(arg: ThunkArg, api: Pick<GetThunkAPI<ThunkApiConfig>, 'getState' | 'extra'>): MaybePromise<boolean | undefined>;
1349 /**
1350 * If `condition` returns `false`, the asyncThunk will be skipped.
1351 * This option allows you to control whether a `rejected` action with `meta.condition == false`
1352 * will be dispatched or not.
1353 *
1354 * @default `false`
1355 */
1356 dispatchConditionRejection?: boolean;
1357 serializeError?: (x: unknown) => GetSerializedErrorType<ThunkApiConfig>;
1358 /**
1359 * A function to use when generating the `requestId` for the request sequence.
1360 *
1361 * @default `nanoid`
1362 */
1363 idGenerator?: (arg: ThunkArg) => string;
1364 } & IsUnknown<GetPendingMeta<ThunkApiConfig>, {
1365 /**
1366 * A method to generate additional properties to be added to `meta` of the pending action.
1367 *
1368 * Using this optional overload will not modify the types correctly, this overload is only in place to support JavaScript users.
1369 * Please use the `ThunkApiConfig` parameter `pendingMeta` to get access to a correctly typed overload
1370 */
1371 getPendingMeta?(base: {
1372 arg: ThunkArg;
1373 requestId: string;
1374 }, api: Pick<GetThunkAPI<ThunkApiConfig>, 'getState' | 'extra'>): GetPendingMeta<ThunkApiConfig>;
1375 }, {
1376 /**
1377 * A method to generate additional properties to be added to `meta` of the pending action.
1378 */
1379 getPendingMeta(base: {
1380 arg: ThunkArg;
1381 requestId: string;
1382 }, api: Pick<GetThunkAPI<ThunkApiConfig>, 'getState' | 'extra'>): GetPendingMeta<ThunkApiConfig>;
1383 }>;
1384 type AsyncThunkPendingActionCreator<ThunkArg, ThunkApiConfig = {}> = ActionCreatorWithPreparedPayload<[
1385 string,
1386 ThunkArg,
1387 GetPendingMeta<ThunkApiConfig>?
1388 ], undefined, string, never, {
1389 arg: ThunkArg;
1390 requestId: string;
1391 requestStatus: 'pending';
1392 } & GetPendingMeta<ThunkApiConfig>>;
1393 type AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig = {}> = ActionCreatorWithPreparedPayload<[
1394 Error | null,
1395 string,
1396 ThunkArg,
1397 GetRejectValue<ThunkApiConfig>?,
1398 GetRejectedMeta<ThunkApiConfig>?
1399 ], GetRejectValue<ThunkApiConfig> | undefined, string, GetSerializedErrorType<ThunkApiConfig>, {
1400 arg: ThunkArg;
1401 requestId: string;
1402 requestStatus: 'rejected';
1403 aborted: boolean;
1404 condition: boolean;
1405 } & (({
1406 rejectedWithValue: false;
1407 } & {
1408 [K in keyof GetRejectedMeta<ThunkApiConfig>]?: undefined;
1409 }) | ({
1410 rejectedWithValue: true;
1411 } & GetRejectedMeta<ThunkApiConfig>))>;
1412 type AsyncThunkFulfilledActionCreator<Returned, ThunkArg, ThunkApiConfig = {}> = ActionCreatorWithPreparedPayload<[
1413 Returned,
1414 string,
1415 ThunkArg,
1416 GetFulfilledMeta<ThunkApiConfig>?
1417 ], Returned, string, never, {
1418 arg: ThunkArg;
1419 requestId: string;
1420 requestStatus: 'fulfilled';
1421 } & GetFulfilledMeta<ThunkApiConfig>>;
1422 /**
1423 * A type describing the return value of `createAsyncThunk`.
1424 * Might be useful for wrapping `createAsyncThunk` in custom abstractions.
1425 *
1426 * @public
1427 */
1428 type AsyncThunk<Returned, ThunkArg, ThunkApiConfig extends AsyncThunkConfig> = AsyncThunkActionCreator<Returned, ThunkArg, ThunkApiConfig> & {
1429 pending: AsyncThunkPendingActionCreator<ThunkArg, ThunkApiConfig>;
1430 rejected: AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig>;
1431 fulfilled: AsyncThunkFulfilledActionCreator<Returned, ThunkArg, ThunkApiConfig>;
1432 settled: (action: any) => action is ReturnType<AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig> | AsyncThunkFulfilledActionCreator<Returned, ThunkArg, ThunkApiConfig>>;
1433 typePrefix: string;
1434 };
1435 type OverrideThunkApiConfigs<OldConfig, NewConfig> = Id<NewConfig & Omit<OldConfig, keyof NewConfig>>;
1436 type CreateAsyncThunkFunction<CurriedThunkApiConfig extends AsyncThunkConfig> = {
1437 /**
1438 *
1439 * @param typePrefix
1440 * @param payloadCreator
1441 * @param options
1442 *
1443 * @public
1444 */
1445 <Returned, ThunkArg = void>(typePrefix: string, payloadCreator: AsyncThunkPayloadCreator<Returned, ThunkArg, CurriedThunkApiConfig>, options?: AsyncThunkOptions<ThunkArg, CurriedThunkApiConfig>): AsyncThunk<Returned, ThunkArg, CurriedThunkApiConfig>;
1446 /**
1447 *
1448 * @param typePrefix
1449 * @param payloadCreator
1450 * @param options
1451 *
1452 * @public
1453 */
1454 <Returned, ThunkArg, ThunkApiConfig extends AsyncThunkConfig>(typePrefix: string, payloadCreator: AsyncThunkPayloadCreator<Returned, ThunkArg, OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>>, options?: AsyncThunkOptions<ThunkArg, OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>>): AsyncThunk<Returned, ThunkArg, OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>>;
1455 };
1456 type CreateAsyncThunk<CurriedThunkApiConfig extends AsyncThunkConfig> = CreateAsyncThunkFunction<CurriedThunkApiConfig> & {
1457 withTypes<ThunkApiConfig extends AsyncThunkConfig>(): CreateAsyncThunk<OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>>;
1458 };
1459 declare const createAsyncThunk: CreateAsyncThunk<AsyncThunkConfig>;
1460 interface UnwrappableAction {
1461 payload: any;
1462 meta?: any;
1463 error?: any;
1464 }
1465 type UnwrappedActionPayload<T extends UnwrappableAction> = Exclude<T, {
1466 error: any;
1467 }>['payload'];
1468 /**
1469 * @public
1470 */
1471 declare function unwrapResult<R extends UnwrappableAction>(action: R): UnwrappedActionPayload<R>;
1472 type WithStrictNullChecks<True, False> = undefined extends boolean ? False : True;
1473
1474 declare const asyncThunkSymbol: unique symbol;
1475 declare const asyncThunkCreator: {
1476 [asyncThunkSymbol]: typeof createAsyncThunk;
1477 };
1478 type InjectIntoConfig<NewReducerPath extends string> = InjectConfig & {
1479 reducerPath?: NewReducerPath;
1480 };
1481 /**
1482 * The return value of `createSlice`
1483 *
1484 * @public
1485 */
1486 interface Slice<State = any, CaseReducers extends SliceCaseReducers<State> = SliceCaseReducers<State>, Name extends string = string, ReducerPath extends string = Name, Selectors extends SliceSelectors<State> = SliceSelectors<State>> {
1487 /**
1488 * The slice name.
1489 */
1490 name: Name;
1491 /**
1492 * The slice reducer path.
1493 */
1494 reducerPath: ReducerPath;
1495 /**
1496 * The slice's reducer.
1497 */
1498 reducer: Reducer<State>;
1499 /**
1500 * Action creators for the types of actions that are handled by the slice
1501 * reducer.
1502 */
1503 actions: CaseReducerActions<CaseReducers, Name>;
1504 /**
1505 * The individual case reducer functions that were passed in the `reducers` parameter.
1506 * This enables reuse and testing if they were defined inline when calling `createSlice`.
1507 */
1508 caseReducers: SliceDefinedCaseReducers<CaseReducers>;
1509 /**
1510 * Provides access to the initial state value given to the slice.
1511 * If a lazy state initializer was provided, it will be called and a fresh value returned.
1512 */
1513 getInitialState: () => State;
1514 /**
1515 * Get localised slice selectors (expects to be called with *just* the slice's state as the first parameter)
1516 */
1517 getSelectors(): Id<SliceDefinedSelectors<State, Selectors, State>>;
1518 /**
1519 * Get globalised slice selectors (`selectState` callback is expected to receive first parameter and return slice state)
1520 */
1521 getSelectors<RootState>(selectState: (rootState: RootState) => State): Id<SliceDefinedSelectors<State, Selectors, RootState>>;
1522 /**
1523 * Selectors that assume the slice's state is `rootState[slice.reducerPath]` (which is usually the case)
1524 *
1525 * Equivalent to `slice.getSelectors((state: RootState) => state[slice.reducerPath])`.
1526 */
1527 get selectors(): Id<SliceDefinedSelectors<State, Selectors, {
1528 [K in ReducerPath]: State;
1529 }>>;
1530 /**
1531 * Inject slice into provided reducer (return value from `combineSlices`), and return injected slice.
1532 */
1533 injectInto<NewReducerPath extends string = ReducerPath>(this: this, injectable: {
1534 inject: (slice: {
1535 reducerPath: string;
1536 reducer: Reducer;
1537 }, config?: InjectConfig) => void;
1538 }, config?: InjectIntoConfig<NewReducerPath>): InjectedSlice<State, CaseReducers, Name, NewReducerPath, Selectors>;
1539 /**
1540 * Select the slice state, using the slice's current reducerPath.
1541 *
1542 * Will throw an error if slice is not found.
1543 */
1544 selectSlice(state: {
1545 [K in ReducerPath]: State;
1546 }): State;
1547 }
1548 /**
1549 * A slice after being called with `injectInto(reducer)`.
1550 *
1551 * Selectors can now be called with an `undefined` value, in which case they use the slice's initial state.
1552 */
1553 type InjectedSlice<State = any, CaseReducers extends SliceCaseReducers<State> = SliceCaseReducers<State>, Name extends string = string, ReducerPath extends string = Name, Selectors extends SliceSelectors<State> = SliceSelectors<State>> = Omit<Slice<State, CaseReducers, Name, ReducerPath, Selectors>, 'getSelectors' | 'selectors'> & {
1554 /**
1555 * Get localised slice selectors (expects to be called with *just* the slice's state as the first parameter)
1556 */
1557 getSelectors(): Id<SliceDefinedSelectors<State, Selectors, State | undefined>>;
1558 /**
1559 * Get globalised slice selectors (`selectState` callback is expected to receive first parameter and return slice state)
1560 */
1561 getSelectors<RootState>(selectState: (rootState: RootState) => State | undefined): Id<SliceDefinedSelectors<State, Selectors, RootState>>;
1562 /**
1563 * Selectors that assume the slice's state is `rootState[slice.name]` (which is usually the case)
1564 *
1565 * Equivalent to `slice.getSelectors((state: RootState) => state[slice.name])`.
1566 */
1567 get selectors(): Id<SliceDefinedSelectors<State, Selectors, {
1568 [K in ReducerPath]?: State | undefined;
1569 }>>;
1570 /**
1571 * Select the slice state, using the slice's current reducerPath.
1572 *
1573 * Returns initial state if slice is not found.
1574 */
1575 selectSlice(state: {
1576 [K in ReducerPath]?: State | undefined;
1577 }): State;
1578 };
1579 /**
1580 * Options for `createSlice()`.
1581 *
1582 * @public
1583 */
1584 interface CreateSliceOptions<State = any, CR extends SliceCaseReducers<State> = SliceCaseReducers<State>, Name extends string = string, ReducerPath extends string = Name, Selectors extends SliceSelectors<State> = SliceSelectors<State>> {
1585 /**
1586 * The slice's name. Used to namespace the generated action types.
1587 */
1588 name: Name;
1589 /**
1590 * The slice's reducer path. Used when injecting into a combined slice reducer.
1591 */
1592 reducerPath?: ReducerPath;
1593 /**
1594 * The initial state that should be used when the reducer is called the first time. This may also be a "lazy initializer" function, which should return an initial state value when called. This will be used whenever the reducer is called with `undefined` as its state value, and is primarily useful for cases like reading initial state from `localStorage`.
1595 */
1596 initialState: State | (() => State);
1597 /**
1598 * A mapping from action types to action-type-specific *case reducer*
1599 * functions. For every action type, a matching action creator will be
1600 * generated using `createAction()`.
1601 */
1602 reducers: ValidateSliceCaseReducers<State, CR> | ((creators: ReducerCreators<State>) => CR);
1603 /**
1604 * A callback that receives a *builder* object to define
1605 * case reducers via calls to `builder.addCase(actionCreatorOrType, reducer)`.
1606 *
1607 *
1608 * @example
1609 ```ts
1610 import { createAction, createSlice, Action } from '@reduxjs/toolkit'
1611 const incrementBy = createAction<number>('incrementBy')
1612 const decrement = createAction('decrement')
1613
1614 interface RejectedAction extends Action {
1615 error: Error
1616 }
1617
1618 function isRejectedAction(action: Action): action is RejectedAction {
1619 return action.type.endsWith('rejected')
1620 }
1621
1622 createSlice({
1623 name: 'counter',
1624 initialState: 0,
1625 reducers: {},
1626 extraReducers: builder => {
1627 builder
1628 .addCase(incrementBy, (state, action) => {
1629 // action is inferred correctly here if using TS
1630 })
1631 // You can chain calls, or have separate `builder.addCase()` lines each time
1632 .addCase(decrement, (state, action) => {})
1633 // You can match a range of action types
1634 .addMatcher(
1635 isRejectedAction,
1636 // `action` will be inferred as a RejectedAction due to isRejectedAction being defined as a type guard
1637 (state, action) => {}
1638 )
1639 // and provide a default case if no other handlers matched
1640 .addDefaultCase((state, action) => {})
1641 }
1642 })
1643 ```
1644 */
1645 extraReducers?: (builder: ActionReducerMapBuilder<State>) => void;
1646 /**
1647 * A map of selectors that receive the slice's state and any additional arguments, and return a result.
1648 */
1649 selectors?: Selectors;
1650 }
1651 declare enum ReducerType {
1652 reducer = "reducer",
1653 reducerWithPrepare = "reducerWithPrepare",
1654 asyncThunk = "asyncThunk"
1655 }
1656 type ReducerDefinition<T extends ReducerType = ReducerType> = {
1657 _reducerDefinitionType: T;
1658 };
1659 type CaseReducerDefinition<S = any, A extends Action = UnknownAction> = CaseReducer<S, A> & ReducerDefinition<ReducerType.reducer>;
1660 /**
1661 * A CaseReducer with a `prepare` method.
1662 *
1663 * @public
1664 */
1665 type CaseReducerWithPrepare<State, Action extends PayloadAction> = {
1666 reducer: CaseReducer<State, Action>;
1667 prepare: PrepareAction<Action['payload']>;
1668 };
1669 type AsyncThunkSliceReducerConfig<State, ThunkArg extends any, Returned = unknown, ThunkApiConfig extends AsyncThunkConfig = {}> = {
1670 pending?: CaseReducer<State, ReturnType<AsyncThunk<Returned, ThunkArg, ThunkApiConfig>['pending']>>;
1671 rejected?: CaseReducer<State, ReturnType<AsyncThunk<Returned, ThunkArg, ThunkApiConfig>['rejected']>>;
1672 fulfilled?: CaseReducer<State, ReturnType<AsyncThunk<Returned, ThunkArg, ThunkApiConfig>['fulfilled']>>;
1673 settled?: CaseReducer<State, ReturnType<AsyncThunk<Returned, ThunkArg, ThunkApiConfig>['rejected' | 'fulfilled']>>;
1674 options?: AsyncThunkOptions<ThunkArg, ThunkApiConfig>;
1675 };
1676 type AsyncThunkSliceReducerDefinition<State, ThunkArg extends any, Returned = unknown, ThunkApiConfig extends AsyncThunkConfig = {}> = AsyncThunkSliceReducerConfig<State, ThunkArg, Returned, ThunkApiConfig> & ReducerDefinition<ReducerType.asyncThunk> & {
1677 payloadCreator: AsyncThunkPayloadCreator<Returned, ThunkArg, ThunkApiConfig>;
1678 };
1679 /**
1680 * Providing these as part of the config would cause circular types, so we disallow passing them
1681 */
1682 type PreventCircular<ThunkApiConfig> = {
1683 [K in keyof ThunkApiConfig]: K extends 'state' | 'dispatch' ? never : ThunkApiConfig[K];
1684 };
1685 interface AsyncThunkCreator<State, CurriedThunkApiConfig extends PreventCircular<AsyncThunkConfig> = PreventCircular<AsyncThunkConfig>> {
1686 <Returned, ThunkArg = void>(payloadCreator: AsyncThunkPayloadCreator<Returned, ThunkArg, CurriedThunkApiConfig>, config?: AsyncThunkSliceReducerConfig<State, ThunkArg, Returned, CurriedThunkApiConfig>): AsyncThunkSliceReducerDefinition<State, ThunkArg, Returned, CurriedThunkApiConfig>;
1687 <Returned, ThunkArg, ThunkApiConfig extends PreventCircular<AsyncThunkConfig> = {}>(payloadCreator: AsyncThunkPayloadCreator<Returned, ThunkArg, ThunkApiConfig>, config?: AsyncThunkSliceReducerConfig<State, ThunkArg, Returned, ThunkApiConfig>): AsyncThunkSliceReducerDefinition<State, ThunkArg, Returned, ThunkApiConfig>;
1688 withTypes<ThunkApiConfig extends PreventCircular<AsyncThunkConfig>>(): AsyncThunkCreator<State, OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>>;
1689 }
1690 interface ReducerCreators<State> {
1691 reducer(caseReducer: CaseReducer<State, PayloadAction>): CaseReducerDefinition<State, PayloadAction>;
1692 reducer<Payload>(caseReducer: CaseReducer<State, PayloadAction<Payload>>): CaseReducerDefinition<State, PayloadAction<Payload>>;
1693 asyncThunk: AsyncThunkCreator<State>;
1694 preparedReducer<Prepare extends PrepareAction<any>>(prepare: Prepare, reducer: CaseReducer<State, ReturnType<_ActionCreatorWithPreparedPayload<Prepare>>>): {
1695 _reducerDefinitionType: ReducerType.reducerWithPrepare;
1696 prepare: Prepare;
1697 reducer: CaseReducer<State, ReturnType<_ActionCreatorWithPreparedPayload<Prepare>>>;
1698 };
1699 }
1700 /**
1701 * The type describing a slice's `reducers` option.
1702 *
1703 * @public
1704 */
1705 type SliceCaseReducers<State> = Record<string, ReducerDefinition> | Record<string, CaseReducer<State, PayloadAction<any>> | CaseReducerWithPrepare<State, PayloadAction<any, string, any, any>>>;
1706 /**
1707 * The type describing a slice's `selectors` option.
1708 */
1709 type SliceSelectors<State> = {
1710 [K: string]: (sliceState: State, ...args: any[]) => any;
1711 };
1712 type SliceActionType<SliceName extends string, ActionName extends keyof any> = ActionName extends string | number ? `${SliceName}/${ActionName}` : string;
1713 /**
1714 * Derives the slice's `actions` property from the `reducers` options
1715 *
1716 * @public
1717 */
1718 type CaseReducerActions<CaseReducers extends SliceCaseReducers<any>, SliceName extends string> = {
1719 [Type in keyof CaseReducers]: CaseReducers[Type] extends infer Definition ? Definition extends {
1720 prepare: any;
1721 } ? ActionCreatorForCaseReducerWithPrepare<Definition, SliceActionType<SliceName, Type>> : Definition extends AsyncThunkSliceReducerDefinition<any, infer ThunkArg, infer Returned, infer ThunkApiConfig> ? AsyncThunk<Returned, ThunkArg, ThunkApiConfig> : Definition extends {
1722 reducer: any;
1723 } ? ActionCreatorForCaseReducer<Definition['reducer'], SliceActionType<SliceName, Type>> : ActionCreatorForCaseReducer<Definition, SliceActionType<SliceName, Type>> : never;
1724 };
1725 /**
1726 * Get a `PayloadActionCreator` type for a passed `CaseReducerWithPrepare`
1727 *
1728 * @internal
1729 */
1730 type ActionCreatorForCaseReducerWithPrepare<CR extends {
1731 prepare: any;
1732 }, Type extends string> = _ActionCreatorWithPreparedPayload<CR['prepare'], Type>;
1733 /**
1734 * Get a `PayloadActionCreator` type for a passed `CaseReducer`
1735 *
1736 * @internal
1737 */
1738 type ActionCreatorForCaseReducer<CR, Type extends string> = CR extends (state: any, action: infer Action) => any ? Action extends {
1739 payload: infer P;
1740 } ? PayloadActionCreator<P, Type> : ActionCreatorWithoutPayload<Type> : ActionCreatorWithoutPayload<Type>;
1741 /**
1742 * Extracts the CaseReducers out of a `reducers` object, even if they are
1743 * tested into a `CaseReducerWithPrepare`.
1744 *
1745 * @internal
1746 */
1747 type SliceDefinedCaseReducers<CaseReducers extends SliceCaseReducers<any>> = {
1748 [Type in keyof CaseReducers]: CaseReducers[Type] extends infer Definition ? Definition extends AsyncThunkSliceReducerDefinition<any, any, any> ? Id<Pick<Required<Definition>, 'fulfilled' | 'rejected' | 'pending' | 'settled'>> : Definition extends {
1749 reducer: infer Reducer;
1750 } ? Reducer : Definition : never;
1751 };
1752 type RemappedSelector<S extends Selector, NewState> = S extends Selector<any, infer R, infer P> ? Selector<NewState, R, P> & {
1753 unwrapped: S;
1754 } : never;
1755 /**
1756 * Extracts the final selector type from the `selectors` object.
1757 *
1758 * Removes the `string` index signature from the default value.
1759 */
1760 type SliceDefinedSelectors<State, Selectors extends SliceSelectors<State>, RootState> = {
1761 [K in keyof Selectors as string extends K ? never : K]: RemappedSelector<Selectors[K], RootState>;
1762 };
1763 /**
1764 * Used on a SliceCaseReducers object.
1765 * Ensures that if a CaseReducer is a `CaseReducerWithPrepare`, that
1766 * the `reducer` and the `prepare` function use the same type of `payload`.
1767 *
1768 * Might do additional such checks in the future.
1769 *
1770 * This type is only ever useful if you want to write your own wrapper around
1771 * `createSlice`. Please don't use it otherwise!
1772 *
1773 * @public
1774 */
1775 type ValidateSliceCaseReducers<S, ACR extends SliceCaseReducers<S>> = ACR & {
1776 [T in keyof ACR]: ACR[T] extends {
1777 reducer(s: S, action?: infer A): any;
1778 } ? {
1779 prepare(...a: never[]): Omit<A, 'type'>;
1780 } : {};
1781 };
1782 interface BuildCreateSliceConfig {
1783 creators?: {
1784 asyncThunk?: typeof asyncThunkCreator;
1785 };
1786 }
1787 declare function buildCreateSlice({ creators }?: BuildCreateSliceConfig): <State, CaseReducers extends SliceCaseReducers<State>, Name extends string, Selectors extends SliceSelectors<State>, ReducerPath extends string = Name>(options: CreateSliceOptions<State, CaseReducers, Name, ReducerPath, Selectors>) => Slice<State, CaseReducers, Name, ReducerPath, Selectors>;
1788 /**
1789 * A function that accepts an initial state, an object full of reducer
1790 * functions, and a "slice name", and automatically generates
1791 * action creators and action types that correspond to the
1792 * reducers and state.
1793 *
1794 * @public
1795 */
1796 declare const createSlice: <State, CaseReducers extends SliceCaseReducers<State>, Name extends string, Selectors extends SliceSelectors<State>, ReducerPath extends string = Name>(options: CreateSliceOptions<State, CaseReducers, Name, ReducerPath, Selectors>) => Slice<State, CaseReducers, Name, ReducerPath, Selectors>;
1797
1798 type AnyFunction = (...args: any) => any;
1799 type AnyCreateSelectorFunction = CreateSelectorFunction<(<F extends AnyFunction>(f: F) => F), <F extends AnyFunction>(f: F) => F>;
1800 type GetSelectorsOptions = {
1801 createSelector?: AnyCreateSelectorFunction;
1802 };
1803
1804 /**
1805 * @public
1806 */
1807 type EntityId = number | string;
1808 /**
1809 * @public
1810 */
1811 type Comparer<T> = (a: T, b: T) => number;
1812 /**
1813 * @public
1814 */
1815 type IdSelector<T, Id extends EntityId> = (model: T) => Id;
1816 /**
1817 * @public
1818 */
1819 type Update<T, Id extends EntityId> = {
1820 id: Id;
1821 changes: Partial<T>;
1822 };
1823 /**
1824 * @public
1825 */
1826 interface EntityState<T, Id extends EntityId> {
1827 ids: Id[];
1828 entities: Record<Id, T>;
1829 }
1830 /**
1831 * @public
1832 */
1833 interface EntityAdapterOptions<T, Id extends EntityId> {
1834 selectId?: IdSelector<T, Id>;
1835 sortComparer?: false | Comparer<T>;
1836 }
1837 type PreventAny<S, T, Id extends EntityId> = CastAny<S, EntityState<T, Id>>;
1838 type DraftableEntityState<T, Id extends EntityId> = EntityState<T, Id> | Draft<EntityState<T, Id>>;
1839 /**
1840 * @public
1841 */
1842 interface EntityStateAdapter<T, Id extends EntityId> {
1843 addOne<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, entity: T): S;
1844 addOne<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, action: PayloadAction<T>): S;
1845 addMany<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, entities: readonly T[] | Record<Id, T>): S;
1846 addMany<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, entities: PayloadAction<readonly T[] | Record<Id, T>>): S;
1847 setOne<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, entity: T): S;
1848 setOne<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, action: PayloadAction<T>): S;
1849 setMany<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, entities: readonly T[] | Record<Id, T>): S;
1850 setMany<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, entities: PayloadAction<readonly T[] | Record<Id, T>>): S;
1851 setAll<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, entities: readonly T[] | Record<Id, T>): S;
1852 setAll<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, entities: PayloadAction<readonly T[] | Record<Id, T>>): S;
1853 removeOne<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, key: Id): S;
1854 removeOne<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, key: PayloadAction<Id>): S;
1855 removeMany<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, keys: readonly Id[]): S;
1856 removeMany<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, keys: PayloadAction<readonly Id[]>): S;
1857 removeAll<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>): S;
1858 updateOne<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, update: Update<T, Id>): S;
1859 updateOne<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, update: PayloadAction<Update<T, Id>>): S;
1860 updateMany<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, updates: ReadonlyArray<Update<T, Id>>): S;
1861 updateMany<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, updates: PayloadAction<ReadonlyArray<Update<T, Id>>>): S;
1862 upsertOne<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, entity: T): S;
1863 upsertOne<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, entity: PayloadAction<T>): S;
1864 upsertMany<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, entities: readonly T[] | Record<Id, T>): S;
1865 upsertMany<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, entities: PayloadAction<readonly T[] | Record<Id, T>>): S;
1866 }
1867 /**
1868 * @public
1869 */
1870 interface EntitySelectors<T, V, IdType extends EntityId> {
1871 selectIds: (state: V) => IdType[];
1872 selectEntities: (state: V) => Record<IdType, T>;
1873 selectAll: (state: V) => T[];
1874 selectTotal: (state: V) => number;
1875 selectById: (state: V, id: IdType) => Id<UncheckedIndexedAccess<T>>;
1876 }
1877 /**
1878 * @public
1879 */
1880 interface EntityStateFactory<T, Id extends EntityId> {
1881 getInitialState(state?: undefined, entities?: Record<Id, T> | readonly T[]): EntityState<T, Id>;
1882 getInitialState<S extends object>(state: S, entities?: Record<Id, T> | readonly T[]): EntityState<T, Id> & S;
1883 }
1884 /**
1885 * @public
1886 */
1887 interface EntityAdapter<T, Id extends EntityId> extends EntityStateAdapter<T, Id>, EntityStateFactory<T, Id>, Required<EntityAdapterOptions<T, Id>> {
1888 getSelectors(selectState?: undefined, options?: GetSelectorsOptions): EntitySelectors<T, EntityState<T, Id>, Id>;
1889 getSelectors<V>(selectState: (state: V) => EntityState<T, Id>, options?: GetSelectorsOptions): EntitySelectors<T, V, Id>;
1890 }
1891
1892 declare function createEntityAdapter<T, Id extends EntityId>(options: WithRequiredProp<EntityAdapterOptions<T, Id>, 'selectId'>): EntityAdapter<T, Id>;
1893 declare function createEntityAdapter<T extends {
1894 id: EntityId;
1895 }>(options?: Omit<EntityAdapterOptions<T, T['id']>, 'selectId'>): EntityAdapter<T, T['id']>;
1896
1897 /** @public */
1898 type ActionMatchingAnyOf<Matchers extends Matcher<any>[]> = ActionFromMatcher<Matchers[number]>;
1899 /** @public */
1900 type ActionMatchingAllOf<Matchers extends Matcher<any>[]> = UnionToIntersection<ActionMatchingAnyOf<Matchers>>;
1901 /**
1902 * A higher-order function that returns a function that may be used to check
1903 * whether an action matches any one of the supplied type guards or action
1904 * creators.
1905 *
1906 * @param matchers The type guards or action creators to match against.
1907 *
1908 * @public
1909 */
1910 declare function isAnyOf<Matchers extends Matcher<any>[]>(...matchers: Matchers): (action: any) => action is ActionMatchingAnyOf<Matchers>;
1911 /**
1912 * A higher-order function that returns a function that may be used to check
1913 * whether an action matches all of the supplied type guards or action
1914 * creators.
1915 *
1916 * @param matchers The type guards or action creators to match against.
1917 *
1918 * @public
1919 */
1920 declare function isAllOf<Matchers extends Matcher<any>[]>(...matchers: Matchers): (action: any) => action is ActionMatchingAllOf<Matchers>;
1921 type UnknownAsyncThunkPendingAction = ReturnType<AsyncThunkPendingActionCreator<unknown>>;
1922 type PendingActionFromAsyncThunk<T extends AnyAsyncThunk> = ActionFromMatcher<T['pending']>;
1923 /**
1924 * A higher-order function that returns a function that may be used to check
1925 * whether an action was created by an async thunk action creator, and that
1926 * the action is pending.
1927 *
1928 * @public
1929 */
1930 declare function isPending(): (action: any) => action is UnknownAsyncThunkPendingAction;
1931 /**
1932 * A higher-order function that returns a function that may be used to check
1933 * whether an action belongs to one of the provided async thunk action creators,
1934 * and that the action is pending.
1935 *
1936 * @param asyncThunks (optional) The async thunk action creators to match against.
1937 *
1938 * @public
1939 */
1940 declare function isPending<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks): (action: any) => action is PendingActionFromAsyncThunk<AsyncThunks[number]>;
1941 /**
1942 * Tests if `action` is a pending thunk action
1943 * @public
1944 */
1945 declare function isPending(action: any): action is UnknownAsyncThunkPendingAction;
1946 type UnknownAsyncThunkRejectedAction = ReturnType<AsyncThunkRejectedActionCreator<unknown, unknown>>;
1947 type RejectedActionFromAsyncThunk<T extends AnyAsyncThunk> = ActionFromMatcher<T['rejected']>;
1948 /**
1949 * A higher-order function that returns a function that may be used to check
1950 * whether an action was created by an async thunk action creator, and that
1951 * the action is rejected.
1952 *
1953 * @public
1954 */
1955 declare function isRejected(): (action: any) => action is UnknownAsyncThunkRejectedAction;
1956 /**
1957 * A higher-order function that returns a function that may be used to check
1958 * whether an action belongs to one of the provided async thunk action creators,
1959 * and that the action is rejected.
1960 *
1961 * @param asyncThunks (optional) The async thunk action creators to match against.
1962 *
1963 * @public
1964 */
1965 declare function isRejected<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks): (action: any) => action is RejectedActionFromAsyncThunk<AsyncThunks[number]>;
1966 /**
1967 * Tests if `action` is a rejected thunk action
1968 * @public
1969 */
1970 declare function isRejected(action: any): action is UnknownAsyncThunkRejectedAction;
1971 type RejectedWithValueActionFromAsyncThunk<T extends AnyAsyncThunk> = ActionFromMatcher<T['rejected']> & (T extends AsyncThunk<any, any, {
1972 rejectValue: infer RejectedValue;
1973 }> ? {
1974 payload: RejectedValue;
1975 } : unknown);
1976 /**
1977 * A higher-order function that returns a function that may be used to check
1978 * whether an action was created by an async thunk action creator, and that
1979 * the action is rejected with value.
1980 *
1981 * @public
1982 */
1983 declare function isRejectedWithValue(): (action: any) => action is UnknownAsyncThunkRejectedAction;
1984 /**
1985 * A higher-order function that returns a function that may be used to check
1986 * whether an action belongs to one of the provided async thunk action creators,
1987 * and that the action is rejected with value.
1988 *
1989 * @param asyncThunks (optional) The async thunk action creators to match against.
1990 *
1991 * @public
1992 */
1993 declare function isRejectedWithValue<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks): (action: any) => action is RejectedWithValueActionFromAsyncThunk<AsyncThunks[number]>;
1994 /**
1995 * Tests if `action` is a rejected thunk action with value
1996 * @public
1997 */
1998 declare function isRejectedWithValue(action: any): action is UnknownAsyncThunkRejectedAction;
1999 type UnknownAsyncThunkFulfilledAction = ReturnType<AsyncThunkFulfilledActionCreator<unknown, unknown>>;
2000 type FulfilledActionFromAsyncThunk<T extends AnyAsyncThunk> = ActionFromMatcher<T['fulfilled']>;
2001 /**
2002 * A higher-order function that returns a function that may be used to check
2003 * whether an action was created by an async thunk action creator, and that
2004 * the action is fulfilled.
2005 *
2006 * @public
2007 */
2008 declare function isFulfilled(): (action: any) => action is UnknownAsyncThunkFulfilledAction;
2009 /**
2010 * A higher-order function that returns a function that may be used to check
2011 * whether an action belongs to one of the provided async thunk action creators,
2012 * and that the action is fulfilled.
2013 *
2014 * @param asyncThunks (optional) The async thunk action creators to match against.
2015 *
2016 * @public
2017 */
2018 declare function isFulfilled<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks): (action: any) => action is FulfilledActionFromAsyncThunk<AsyncThunks[number]>;
2019 /**
2020 * Tests if `action` is a fulfilled thunk action
2021 * @public
2022 */
2023 declare function isFulfilled(action: any): action is UnknownAsyncThunkFulfilledAction;
2024 type UnknownAsyncThunkAction = UnknownAsyncThunkPendingAction | UnknownAsyncThunkRejectedAction | UnknownAsyncThunkFulfilledAction;
2025 type AnyAsyncThunk = {
2026 pending: {
2027 match: (action: any) => action is any;
2028 };
2029 fulfilled: {
2030 match: (action: any) => action is any;
2031 };
2032 rejected: {
2033 match: (action: any) => action is any;
2034 };
2035 };
2036 type ActionsFromAsyncThunk<T extends AnyAsyncThunk> = ActionFromMatcher<T['pending']> | ActionFromMatcher<T['fulfilled']> | ActionFromMatcher<T['rejected']>;
2037 /**
2038 * A higher-order function that returns a function that may be used to check
2039 * whether an action was created by an async thunk action creator.
2040 *
2041 * @public
2042 */
2043 declare function isAsyncThunkAction(): (action: any) => action is UnknownAsyncThunkAction;
2044 /**
2045 * A higher-order function that returns a function that may be used to check
2046 * whether an action belongs to one of the provided async thunk action creators.
2047 *
2048 * @param asyncThunks (optional) The async thunk action creators to match against.
2049 *
2050 * @public
2051 */
2052 declare function isAsyncThunkAction<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks): (action: any) => action is ActionsFromAsyncThunk<AsyncThunks[number]>;
2053 /**
2054 * Tests if `action` is a thunk action
2055 * @public
2056 */
2057 declare function isAsyncThunkAction(action: any): action is UnknownAsyncThunkAction;
2058
2059 /**
2060 *
2061 * @public
2062 */
2063 declare let nanoid: (size?: number) => string;
2064
2065 declare class TaskAbortError implements SerializedError {
2066 code: string | undefined;
2067 name: string;
2068 message: string;
2069 constructor(code: string | undefined);
2070 }
2071
2072 /**
2073 * Types copied from RTK
2074 */
2075 /** @internal */
2076 type TypedActionCreatorWithMatchFunction<Type extends string> = TypedActionCreator<Type> & {
2077 match: MatchFunction<any>;
2078 };
2079 /** @internal */
2080 type AnyListenerPredicate<State> = (action: UnknownAction, currentState: State, originalState: State) => boolean;
2081 /** @public */
2082 type ListenerPredicate<ActionType extends Action, State> = (action: UnknownAction, currentState: State, originalState: State) => action is ActionType;
2083 /** @public */
2084 interface ConditionFunction<State> {
2085 (predicate: AnyListenerPredicate<State>, timeout?: number): Promise<boolean>;
2086 (predicate: AnyListenerPredicate<State>, timeout?: number): Promise<boolean>;
2087 (predicate: () => boolean, timeout?: number): Promise<boolean>;
2088 }
2089 /** @internal */
2090 type MatchFunction<T> = (v: any) => v is T;
2091 /** @public */
2092 interface ForkedTaskAPI {
2093 /**
2094 * Returns a promise that resolves when `waitFor` resolves or
2095 * rejects if the task or the parent listener has been cancelled or is completed.
2096 */
2097 pause<W>(waitFor: Promise<W>): Promise<W>;
2098 /**
2099 * Returns a promise that resolves after `timeoutMs` or
2100 * rejects if the task or the parent listener has been cancelled or is completed.
2101 * @param timeoutMs
2102 */
2103 delay(timeoutMs: number): Promise<void>;
2104 /**
2105 * An abort signal whose `aborted` property is set to `true`
2106 * if the task execution is either aborted or completed.
2107 * @see https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal
2108 */
2109 signal: AbortSignal;
2110 }
2111 /** @public */
2112 interface AsyncTaskExecutor<T> {
2113 (forkApi: ForkedTaskAPI): Promise<T>;
2114 }
2115 /** @public */
2116 interface SyncTaskExecutor<T> {
2117 (forkApi: ForkedTaskAPI): T;
2118 }
2119 /** @public */
2120 type ForkedTaskExecutor<T> = AsyncTaskExecutor<T> | SyncTaskExecutor<T>;
2121 /** @public */
2122 type TaskResolved<T> = {
2123 readonly status: 'ok';
2124 readonly value: T;
2125 };
2126 /** @public */
2127 type TaskRejected = {
2128 readonly status: 'rejected';
2129 readonly error: unknown;
2130 };
2131 /** @public */
2132 type TaskCancelled = {
2133 readonly status: 'cancelled';
2134 readonly error: TaskAbortError;
2135 };
2136 /** @public */
2137 type TaskResult<Value> = TaskResolved<Value> | TaskRejected | TaskCancelled;
2138 /** @public */
2139 interface ForkedTask<T> {
2140 /**
2141 * A promise that resolves when the task is either completed or cancelled or rejects
2142 * if parent listener execution is cancelled or completed.
2143 *
2144 * ### Example
2145 * ```ts
2146 * const result = await fork(async (forkApi) => Promise.resolve(4)).result
2147 *
2148 * if(result.status === 'ok') {
2149 * console.log(result.value) // logs 4
2150 * }}
2151 * ```
2152 */
2153 result: Promise<TaskResult<T>>;
2154 /**
2155 * Cancel task if it is in progress or not yet started,
2156 * it is noop otherwise.
2157 */
2158 cancel(): void;
2159 }
2160 /** @public */
2161 interface ForkOptions {
2162 /**
2163 * If true, causes the parent task to not be marked as complete until
2164 * all autoJoined forks have completed or failed.
2165 */
2166 autoJoin: boolean;
2167 }
2168 /** @public */
2169 interface ListenerEffectAPI<State, DispatchType extends Dispatch, ExtraArgument = unknown> extends MiddlewareAPI<DispatchType, State> {
2170 /**
2171 * Returns the store state as it existed when the action was originally dispatched, _before_ the reducers ran.
2172 *
2173 * ### Synchronous invocation
2174 *
2175 * This function can **only** be invoked **synchronously**, it throws error otherwise.
2176 *
2177 * @example
2178 *
2179 * ```ts
2180 * middleware.startListening({
2181 * predicate: () => true,
2182 * async effect(_, { getOriginalState }) {
2183 * getOriginalState(); // sync: OK!
2184 *
2185 * setTimeout(getOriginalState, 0); // async: throws Error
2186 *
2187 * await Promise().resolve();
2188 *
2189 * getOriginalState() // async: throws Error
2190 * }
2191 * })
2192 * ```
2193 */
2194 getOriginalState: () => State;
2195 /**
2196 * Removes the listener entry from the middleware and prevent future instances of the listener from running.
2197 *
2198 * It does **not** cancel any active instances.
2199 */
2200 unsubscribe(): void;
2201 /**
2202 * It will subscribe a listener if it was previously removed, noop otherwise.
2203 */
2204 subscribe(): void;
2205 /**
2206 * Returns a promise that resolves when the input predicate returns `true` or
2207 * rejects if the listener has been cancelled or is completed.
2208 *
2209 * The return value is `true` if the predicate succeeds or `false` if a timeout is provided and expires first.
2210 *
2211 * ### Example
2212 *
2213 * ```ts
2214 * const updateBy = createAction<number>('counter/updateBy');
2215 *
2216 * middleware.startListening({
2217 * actionCreator: updateBy,
2218 * async effect(_, { condition }) {
2219 * // wait at most 3s for `updateBy` actions.
2220 * if(await condition(updateBy.match, 3_000)) {
2221 * // `updateBy` has been dispatched twice in less than 3s.
2222 * }
2223 * }
2224 * })
2225 * ```
2226 */
2227 condition: ConditionFunction<State>;
2228 /**
2229 * Returns a promise that resolves when the input predicate returns `true` or
2230 * rejects if the listener has been cancelled or is completed.
2231 *
2232 * The return value is the `[action, currentState, previousState]` combination that the predicate saw as arguments.
2233 *
2234 * The promise resolves to null if a timeout is provided and expires first,
2235 *
2236 * ### Example
2237 *
2238 * ```ts
2239 * const updateBy = createAction<number>('counter/updateBy');
2240 *
2241 * middleware.startListening({
2242 * actionCreator: updateBy,
2243 * async effect(_, { take }) {
2244 * const [{ payload }] = await take(updateBy.match);
2245 * console.log(payload); // logs 5;
2246 * }
2247 * })
2248 *
2249 * store.dispatch(updateBy(5));
2250 * ```
2251 */
2252 take: TakePattern<State>;
2253 /**
2254 * Cancels all other running instances of this same listener except for the one that made this call.
2255 */
2256 cancelActiveListeners: () => void;
2257 /**
2258 * Cancels the instance of this listener that made this call.
2259 */
2260 cancel: () => void;
2261 /**
2262 * Throws a `TaskAbortError` if this listener has been cancelled
2263 */
2264 throwIfCancelled: () => void;
2265 /**
2266 * An abort signal whose `aborted` property is set to `true`
2267 * if the listener execution is either aborted or completed.
2268 * @see https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal
2269 */
2270 signal: AbortSignal;
2271 /**
2272 * Returns a promise that resolves after `timeoutMs` or
2273 * rejects if the listener has been cancelled or is completed.
2274 */
2275 delay(timeoutMs: number): Promise<void>;
2276 /**
2277 * Queues in the next microtask the execution of a task.
2278 * @param executor
2279 * @param options
2280 */
2281 fork<T>(executor: ForkedTaskExecutor<T>, options?: ForkOptions): ForkedTask<T>;
2282 /**
2283 * Returns a promise that resolves when `waitFor` resolves or
2284 * rejects if the listener has been cancelled or is completed.
2285 * @param promise
2286 */
2287 pause<M>(promise: Promise<M>): Promise<M>;
2288 extra: ExtraArgument;
2289 }
2290 /** @public */
2291 type ListenerEffect<ActionType extends Action, State, DispatchType extends Dispatch, ExtraArgument = unknown> = (action: ActionType, api: ListenerEffectAPI<State, DispatchType, ExtraArgument>) => void | Promise<void>;
2292 /**
2293 * @public
2294 * Additional infos regarding the error raised.
2295 */
2296 interface ListenerErrorInfo {
2297 /**
2298 * Which function has generated the exception.
2299 */
2300 raisedBy: 'effect' | 'predicate';
2301 }
2302 /**
2303 * @public
2304 * Gets notified with synchronous and asynchronous errors raised by `listeners` or `predicates`.
2305 * @param error The thrown error.
2306 * @param errorInfo Additional information regarding the thrown error.
2307 */
2308 interface ListenerErrorHandler {
2309 (error: unknown, errorInfo: ListenerErrorInfo): void;
2310 }
2311 /** @public */
2312 interface CreateListenerMiddlewareOptions<ExtraArgument = unknown> {
2313 extra?: ExtraArgument;
2314 /**
2315 * Receives synchronous errors that are raised by `listener` and `listenerOption.predicate`.
2316 */
2317 onError?: ListenerErrorHandler;
2318 }
2319 /** @public */
2320 type ListenerMiddleware<State = unknown, DispatchType extends ThunkDispatch<State, unknown, Action> = ThunkDispatch<State, unknown, UnknownAction>, ExtraArgument = unknown> = Middleware<{
2321 (action: Action<'listenerMiddleware/add'>): UnsubscribeListener;
2322 }, State, DispatchType>;
2323 /** @public */
2324 interface ListenerMiddlewareInstance<StateType = unknown, DispatchType extends ThunkDispatch<StateType, unknown, Action> = ThunkDispatch<StateType, unknown, UnknownAction>, ExtraArgument = unknown> {
2325 middleware: ListenerMiddleware<StateType, DispatchType, ExtraArgument>;
2326 startListening: AddListenerOverloads<UnsubscribeListener, StateType, DispatchType, ExtraArgument> & TypedStartListening<StateType, DispatchType, ExtraArgument>;
2327 stopListening: RemoveListenerOverloads<StateType, DispatchType> & TypedStopListening<StateType, DispatchType>;
2328 /**
2329 * Unsubscribes all listeners, cancels running listeners and tasks.
2330 */
2331 clearListeners: () => void;
2332 }
2333 /**
2334 * API Function Overloads
2335 */
2336 /** @public */
2337 type TakePatternOutputWithoutTimeout<State, Predicate extends AnyListenerPredicate<State>> = Predicate extends MatchFunction<infer ActionType> ? Promise<[ActionType, State, State]> : Promise<[UnknownAction, State, State]>;
2338 /** @public */
2339 type TakePatternOutputWithTimeout<State, Predicate extends AnyListenerPredicate<State>> = Predicate extends MatchFunction<infer ActionType> ? Promise<[ActionType, State, State] | null> : Promise<[UnknownAction, State, State] | null>;
2340 /** @public */
2341 interface TakePattern<State> {
2342 <Predicate extends AnyListenerPredicate<State>>(predicate: Predicate): TakePatternOutputWithoutTimeout<State, Predicate>;
2343 <Predicate extends AnyListenerPredicate<State>>(predicate: Predicate, timeout: number): TakePatternOutputWithTimeout<State, Predicate>;
2344 <Predicate extends AnyListenerPredicate<State>>(predicate: Predicate, timeout?: number | undefined): TakePatternOutputWithTimeout<State, Predicate>;
2345 }
2346 /** @public */
2347 interface UnsubscribeListenerOptions {
2348 cancelActive?: true;
2349 }
2350 /** @public */
2351 type UnsubscribeListener = (unsubscribeOptions?: UnsubscribeListenerOptions) => void;
2352 /**
2353 * @public
2354 * The possible overloads and options for defining a listener. The return type of each function is specified as a generic arg, so the overloads can be reused for multiple different functions
2355 */
2356 type AddListenerOverloads<Return, StateType = unknown, DispatchType extends Dispatch = ThunkDispatch<StateType, unknown, UnknownAction>, ExtraArgument = unknown, AdditionalOptions = unknown> = {
2357 /** Accepts a "listener predicate" that is also a TS type predicate for the action*/
2358 <MiddlewareActionType extends UnknownAction, ListenerPredicateType extends ListenerPredicate<MiddlewareActionType, StateType>>(options: {
2359 actionCreator?: never;
2360 type?: never;
2361 matcher?: never;
2362 predicate: ListenerPredicateType;
2363 effect: ListenerEffect<ListenerPredicateGuardedActionType<ListenerPredicateType>, StateType, DispatchType, ExtraArgument>;
2364 } & AdditionalOptions): Return;
2365 /** Accepts an RTK action creator, like `incrementByAmount` */
2366 <ActionCreatorType extends TypedActionCreatorWithMatchFunction<any>>(options: {
2367 actionCreator: ActionCreatorType;
2368 type?: never;
2369 matcher?: never;
2370 predicate?: never;
2371 effect: ListenerEffect<ReturnType<ActionCreatorType>, StateType, DispatchType, ExtraArgument>;
2372 } & AdditionalOptions): Return;
2373 /** Accepts a specific action type string */
2374 <T extends string>(options: {
2375 actionCreator?: never;
2376 type: T;
2377 matcher?: never;
2378 predicate?: never;
2379 effect: ListenerEffect<Action<T>, StateType, DispatchType, ExtraArgument>;
2380 } & AdditionalOptions): Return;
2381 /** Accepts an RTK matcher function, such as `incrementByAmount.match` */
2382 <MatchFunctionType extends MatchFunction<UnknownAction>>(options: {
2383 actionCreator?: never;
2384 type?: never;
2385 matcher: MatchFunctionType;
2386 predicate?: never;
2387 effect: ListenerEffect<GuardedType<MatchFunctionType>, StateType, DispatchType, ExtraArgument>;
2388 } & AdditionalOptions): Return;
2389 /** Accepts a "listener predicate" that just returns a boolean, no type assertion */
2390 <ListenerPredicateType extends AnyListenerPredicate<StateType>>(options: {
2391 actionCreator?: never;
2392 type?: never;
2393 matcher?: never;
2394 predicate: ListenerPredicateType;
2395 effect: ListenerEffect<UnknownAction, StateType, DispatchType, ExtraArgument>;
2396 } & AdditionalOptions): Return;
2397 };
2398 /** @public */
2399 type RemoveListenerOverloads<StateType = unknown, DispatchType extends Dispatch = ThunkDispatch<StateType, unknown, UnknownAction>, ExtraArgument = unknown> = AddListenerOverloads<boolean, StateType, DispatchType, ExtraArgument, UnsubscribeListenerOptions>;
2400 /**
2401 * A "pre-typed" version of `addListenerAction`, so the listener args are well-typed
2402 *
2403 * @public
2404 */
2405 type TypedAddListener<StateType, DispatchType extends Dispatch = ThunkDispatch<StateType, unknown, UnknownAction>, ExtraArgument = unknown, Payload = ListenerEntry<StateType, DispatchType>, T extends string = 'listenerMiddleware/add'> = BaseActionCreator<Payload, T> & AddListenerOverloads<PayloadAction<Payload, T>, StateType, DispatchType, ExtraArgument> & {
2406 /**
2407 * Creates a "pre-typed" version of `addListener`
2408 * where the `state`, `dispatch` and `extra` types are predefined.
2409 *
2410 * This allows you to set the `state`, `dispatch` and `extra` types once,
2411 * eliminating the need to specify them with every `addListener` call.
2412 *
2413 * @returns A pre-typed `addListener` with the state, dispatch and extra types already defined.
2414 *
2415 * @example
2416 * ```ts
2417 * import { addListener } from '@reduxjs/toolkit'
2418 *
2419 * export const addAppListener = addListener.withTypes<RootState, AppDispatch, ExtraArguments>()
2420 * ```
2421 *
2422 * @template OverrideStateType - The specific type of state the middleware listener operates on.
2423 * @template OverrideDispatchType - The specific type of the dispatch function.
2424 * @template OverrideExtraArgument - The specific type of the extra object.
2425 *
2426 * @since 2.1.0
2427 */
2428 withTypes: <OverrideStateType extends StateType, OverrideDispatchType extends Dispatch = ThunkDispatch<OverrideStateType, unknown, UnknownAction>, OverrideExtraArgument = unknown>() => TypedAddListener<OverrideStateType, OverrideDispatchType, OverrideExtraArgument>;
2429 };
2430 /**
2431 * A "pre-typed" version of `removeListenerAction`, so the listener args are well-typed
2432 *
2433 * @public
2434 */
2435 type TypedRemoveListener<StateType, DispatchType extends Dispatch = ThunkDispatch<StateType, unknown, UnknownAction>, ExtraArgument = unknown, Payload = ListenerEntry<StateType, DispatchType>, T extends string = 'listenerMiddleware/remove'> = BaseActionCreator<Payload, T> & AddListenerOverloads<PayloadAction<Payload, T>, StateType, DispatchType, ExtraArgument, UnsubscribeListenerOptions> & {
2436 /**
2437 * Creates a "pre-typed" version of `removeListener`
2438 * where the `state`, `dispatch` and `extra` types are predefined.
2439 *
2440 * This allows you to set the `state`, `dispatch` and `extra` types once,
2441 * eliminating the need to specify them with every `removeListener` call.
2442 *
2443 * @returns A pre-typed `removeListener` with the state, dispatch and extra
2444 * types already defined.
2445 *
2446 * @example
2447 * ```ts
2448 * import { removeListener } from '@reduxjs/toolkit'
2449 *
2450 * export const removeAppListener = removeListener.withTypes<
2451 * RootState,
2452 * AppDispatch,
2453 * ExtraArguments
2454 * >()
2455 * ```
2456 *
2457 * @template OverrideStateType - The specific type of state the middleware listener operates on.
2458 * @template OverrideDispatchType - The specific type of the dispatch function.
2459 * @template OverrideExtraArgument - The specific type of the extra object.
2460 *
2461 * @since 2.1.0
2462 */
2463 withTypes: <OverrideStateType extends StateType, OverrideDispatchType extends Dispatch = ThunkDispatch<OverrideStateType, unknown, UnknownAction>, OverrideExtraArgument = unknown>() => TypedRemoveListener<OverrideStateType, OverrideDispatchType, OverrideExtraArgument>;
2464 };
2465 /**
2466 * A "pre-typed" version of `middleware.startListening`, so the listener args are well-typed
2467 *
2468 * @public
2469 */
2470 type TypedStartListening<StateType, DispatchType extends Dispatch = ThunkDispatch<StateType, unknown, UnknownAction>, ExtraArgument = unknown> = AddListenerOverloads<UnsubscribeListener, StateType, DispatchType, ExtraArgument> & {
2471 /**
2472 * Creates a "pre-typed" version of
2473 * {@linkcode ListenerMiddlewareInstance.startListening startListening}
2474 * where the `state`, `dispatch` and `extra` types are predefined.
2475 *
2476 * This allows you to set the `state`, `dispatch` and `extra` types once,
2477 * eliminating the need to specify them with every
2478 * {@linkcode ListenerMiddlewareInstance.startListening startListening} call.
2479 *
2480 * @returns A pre-typed `startListening` with the state, dispatch and extra types already defined.
2481 *
2482 * @example
2483 * ```ts
2484 * import { createListenerMiddleware } from '@reduxjs/toolkit'
2485 *
2486 * const listenerMiddleware = createListenerMiddleware()
2487 *
2488 * export const startAppListening = listenerMiddleware.startListening.withTypes<
2489 * RootState,
2490 * AppDispatch,
2491 * ExtraArguments
2492 * >()
2493 * ```
2494 *
2495 * @template OverrideStateType - The specific type of state the middleware listener operates on.
2496 * @template OverrideDispatchType - The specific type of the dispatch function.
2497 * @template OverrideExtraArgument - The specific type of the extra object.
2498 *
2499 * @since 2.1.0
2500 */
2501 withTypes: <OverrideStateType extends StateType, OverrideDispatchType extends Dispatch = ThunkDispatch<OverrideStateType, unknown, UnknownAction>, OverrideExtraArgument = unknown>() => TypedStartListening<OverrideStateType, OverrideDispatchType, OverrideExtraArgument>;
2502 };
2503 /**
2504 * A "pre-typed" version of `middleware.stopListening`, so the listener args are well-typed
2505 *
2506 * @public
2507 */
2508 type TypedStopListening<StateType, DispatchType extends Dispatch = ThunkDispatch<StateType, unknown, UnknownAction>, ExtraArgument = unknown> = RemoveListenerOverloads<StateType, DispatchType, ExtraArgument> & {
2509 /**
2510 * Creates a "pre-typed" version of
2511 * {@linkcode ListenerMiddlewareInstance.stopListening stopListening}
2512 * where the `state`, `dispatch` and `extra` types are predefined.
2513 *
2514 * This allows you to set the `state`, `dispatch` and `extra` types once,
2515 * eliminating the need to specify them with every
2516 * {@linkcode ListenerMiddlewareInstance.stopListening stopListening} call.
2517 *
2518 * @returns A pre-typed `stopListening` with the state, dispatch and extra types already defined.
2519 *
2520 * @example
2521 * ```ts
2522 * import { createListenerMiddleware } from '@reduxjs/toolkit'
2523 *
2524 * const listenerMiddleware = createListenerMiddleware()
2525 *
2526 * export const stopAppListening = listenerMiddleware.stopListening.withTypes<
2527 * RootState,
2528 * AppDispatch,
2529 * ExtraArguments
2530 * >()
2531 * ```
2532 *
2533 * @template OverrideStateType - The specific type of state the middleware listener operates on.
2534 * @template OverrideDispatchType - The specific type of the dispatch function.
2535 * @template OverrideExtraArgument - The specific type of the extra object.
2536 *
2537 * @since 2.1.0
2538 */
2539 withTypes: <OverrideStateType extends StateType, OverrideDispatchType extends Dispatch = ThunkDispatch<OverrideStateType, unknown, UnknownAction>, OverrideExtraArgument = unknown>() => TypedStopListening<OverrideStateType, OverrideDispatchType, OverrideExtraArgument>;
2540 };
2541 /**
2542 * Internal Types
2543 */
2544 /** @internal An single listener entry */
2545 type ListenerEntry<State = unknown, DispatchType extends Dispatch = Dispatch> = {
2546 id: string;
2547 effect: ListenerEffect<any, State, DispatchType>;
2548 unsubscribe: () => void;
2549 pending: Set<AbortController>;
2550 type?: string;
2551 predicate: ListenerPredicate<UnknownAction, State>;
2552 };
2553 /**
2554 * Utility Types
2555 */
2556 /** @public */
2557 type GuardedType<T> = T extends (x: any, ...args: any[]) => x is infer T ? T : never;
2558 /** @public */
2559 type ListenerPredicateGuardedActionType<T> = T extends ListenerPredicate<infer ActionType, any> ? ActionType : never;
2560
2561 /**
2562 * @public
2563 */
2564 declare const addListener: TypedAddListener<unknown>;
2565 /**
2566 * @public
2567 */
2568 declare const clearAllListeners: ActionCreatorWithoutPayload<"listenerMiddleware/removeAll">;
2569 /**
2570 * @public
2571 */
2572 declare const removeListener: TypedRemoveListener<unknown>;
2573 /**
2574 * @public
2575 */
2576 declare const createListenerMiddleware: <StateType = unknown, DispatchType extends Dispatch<Action> = ThunkDispatch<StateType, unknown, UnknownAction>, ExtraArgument = unknown>(middlewareOptions?: CreateListenerMiddlewareOptions<ExtraArgument>) => ListenerMiddlewareInstance<StateType, DispatchType, ExtraArgument>;
2577
2578 type MiddlewareApiConfig = {
2579 state?: unknown;
2580 dispatch?: Dispatch;
2581 };
2582 type GetDispatchType<MiddlewareApiConfig> = MiddlewareApiConfig extends {
2583 dispatch: infer DispatchType;
2584 } ? FallbackIfUnknown<DispatchType, Dispatch> : Dispatch;
2585 type AddMiddleware<State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>> = {
2586 (...middlewares: Middleware<any, State, DispatchType>[]): void;
2587 withTypes<MiddlewareConfig extends MiddlewareApiConfig>(): AddMiddleware<GetState<MiddlewareConfig>, GetDispatchType<MiddlewareConfig>>;
2588 };
2589 type WithMiddleware<State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>> = BaseActionCreator<Middleware<any, State, DispatchType>[], 'dynamicMiddleware/add', {
2590 instanceId: string;
2591 }> & {
2592 <Middlewares extends Middleware<any, State, DispatchType>[]>(...middlewares: Middlewares): PayloadAction<Middlewares, 'dynamicMiddleware/add', {
2593 instanceId: string;
2594 }>;
2595 withTypes<MiddlewareConfig extends MiddlewareApiConfig>(): WithMiddleware<GetState<MiddlewareConfig>, GetDispatchType<MiddlewareConfig>>;
2596 };
2597 interface DynamicDispatch {
2598 <Middlewares extends Middleware<any>[]>(action: PayloadAction<Middlewares, 'dynamicMiddleware/add'>): ExtractDispatchExtensions<Middlewares> & this;
2599 }
2600 type DynamicMiddleware<State = unknown, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>> = Middleware<DynamicDispatch, State, DispatchType>;
2601 type DynamicMiddlewareInstance<State = unknown, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>> = {
2602 middleware: DynamicMiddleware<State, DispatchType>;
2603 addMiddleware: AddMiddleware<State, DispatchType>;
2604 withMiddleware: WithMiddleware<State, DispatchType>;
2605 instanceId: string;
2606 };
2607
2608 declare const createDynamicMiddleware: <State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>>() => DynamicMiddlewareInstance<State, DispatchType>;
2609
2610 /**
2611 * Adapted from React: https://github.com/facebook/react/blob/master/packages/shared/formatProdErrorMessage.js
2612 *
2613 * Do not require this module directly! Use normal throw error calls. These messages will be replaced with error codes
2614 * during build.
2615 * @param {number} code
2616 */
2617 declare function formatProdErrorMessage(code: number): string;
2618
2619 export { type ActionCreatorInvariantMiddlewareOptions, type ActionCreatorWithNonInferrablePayload, type ActionCreatorWithOptionalPayload, type ActionCreatorWithPayload, type ActionCreatorWithPreparedPayload, type ActionCreatorWithoutPayload, type ActionMatchingAllOf, type ActionMatchingAnyOf, type ActionReducerMapBuilder, type Actions, type AddMiddleware, type AnyListenerPredicate, type AsyncTaskExecutor, type AsyncThunk, type AsyncThunkAction, type AsyncThunkOptions, type AsyncThunkPayloadCreator, type AsyncThunkPayloadCreatorReturnValue, type AutoBatchOptions, type CaseReducer, type CaseReducerActions, type CaseReducerWithPrepare, type CaseReducers, type CombinedSliceReducer, type Comparer, type ConfigureStoreOptions, type CreateAsyncThunkFunction, type CreateListenerMiddlewareOptions, type CreateSliceOptions, type DevToolsEnhancerOptions, type DynamicDispatch, type DynamicMiddlewareInstance, type EnhancedStore, type EntityAdapter, type EntityId, type EntitySelectors, type EntityState, type EntityStateAdapter, type ForkedTask, type ForkedTaskAPI, type ForkedTaskExecutor, type GetDispatchType as GetDispatch, type GetState, type GetThunkAPI, type IdSelector, type ImmutableStateInvariantMiddlewareOptions, type ListenerEffect, type ListenerEffectAPI, type ListenerErrorHandler, type ListenerMiddleware, type ListenerMiddlewareInstance, type MiddlewareApiConfig, type PayloadAction, type PayloadActionCreator, type PrepareAction, type ReducerCreators, ReducerType, SHOULD_AUTOBATCH, type SafePromise, type SerializableStateInvariantMiddlewareOptions, type SerializedError, type Slice, type SliceCaseReducers, type SliceSelectors, type SyncTaskExecutor, type ExtractDispatchExtensions as TSHelpersExtractDispatchExtensions, TaskAbortError, type TaskCancelled, type TaskRejected, type TaskResolved, type TaskResult, Tuple, type TypedAddListener, type TypedRemoveListener, type TypedStartListening, type TypedStopListening, type UnsubscribeListener, type UnsubscribeListenerOptions, type Update, type ValidateSliceCaseReducers, type WithSlice, addListener, asyncThunkCreator, autoBatchEnhancer, buildCreateSlice, clearAllListeners, combineSlices, configureStore, createAction, createActionCreatorInvariantMiddleware, createAsyncThunk, createDraftSafeSelector, createDraftSafeSelectorCreator, createDynamicMiddleware, createEntityAdapter, createImmutableStateInvariantMiddleware, createListenerMiddleware, createReducer, createSerializableStateInvariantMiddleware, createSlice, findNonSerializableValue, formatProdErrorMessage, isActionCreator, isAllOf, isAnyOf, isAsyncThunkAction, isFSA as isFluxStandardAction, isFulfilled, isImmutableDefault, isPending, isPlain, isRejected, isRejectedWithValue, miniSerializeError, nanoid, prepareAutoBatched, removeListener, unwrapResult };