source: node_modules/@reduxjs/toolkit/dist/index.d.mts@ a762898

Last change on this file since a762898 was a762898, checked in by istevanoska <ilinastevanoska@…>, 5 months ago

Added visualizations

  • Property mode set to 100644
File size: 119.7 KB
Line 
1import { ActionCreator, Action, Middleware, StoreEnhancer, UnknownAction, Reducer, ReducersMapObject, Store, Dispatch, StateFromReducersMapObject, PreloadedStateShapeFromReducersMapObject, MiddlewareAPI } from 'redux';
2export * from 'redux';
3import { Draft } from 'immer';
4export { Draft, WritableDraft, produce as createNextState, current, freeze, isDraft, original } from 'immer';
5import * as reselect from 'reselect';
6import { weakMapMemoize, createSelectorCreator, Selector, CreateSelectorFunction } from 'reselect';
7export { OutputSelector, Selector, createSelector, createSelectorCreator, lruMemoize, weakMapMemoize } from 'reselect';
8import { ThunkMiddleware, ThunkDispatch } from 'redux-thunk';
9export { ThunkAction, ThunkDispatch, ThunkMiddleware } from 'redux-thunk';
10import { UncheckedIndexedAccess } from './uncheckedindexed.js';
11
12declare 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 */
20declare const createDraftSafeSelector: reselect.CreateSelectorFunction<typeof weakMapMemoize, typeof weakMapMemoize, any>;
21
22/**
23 * @public
24 */
25interface 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
222interface 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}
231declare 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 */
242declare function isPlain(val: any): boolean;
243interface NonSerializableValue {
244 keyPath: string;
245 value: unknown;
246}
247type IgnorePaths = readonly (string | RegExp)[];
248/**
249 * @public
250 */
251declare 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 */
257interface 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 */
315declare function createSerializableStateInvariantMiddleware(options?: SerializableStateInvariantMiddlewareOptions): Middleware;
316
317/**
318 * The default `isImmutable` function.
319 *
320 * @public
321 */
322declare function isImmutableDefault(value: unknown): boolean;
323type IsImmutableFunc = (value: any) => boolean;
324/**
325 * Options for `createImmutableStateInvariantMiddleware()`.
326 *
327 * @public
328 */
329interface 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 */
355declare function createImmutableStateInvariantMiddleware(options?: ImmutableStateInvariantMiddlewareOptions): Middleware;
356
357declare 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 */
375type IsAny<T, True, False = never> = true | false extends (T extends never ? true : false) ? True : False;
376type 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 */
383type IsUnknown<T, True, False = never> = unknown extends T ? IsAny<T, False, True> : False;
384type FallbackIfUnknown<T, Fallback> = IsUnknown<T, Fallback, T>;
385/**
386 * @internal
387 */
388type IfMaybeUndefined<P, True, False> = [undefined] extends [P] ? True : False;
389/**
390 * @internal
391 */
392type IfVoid<P, True, False> = [void] extends [P] ? True : False;
393/**
394 * @internal
395 */
396type 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 */
405type AtLeastTS35<True, False> = [True, False][IsUnknown<ReturnType<(<T>() => T)>, 0, 1>];
406/**
407 * @internal
408 */
409type 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 */
413type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (k: infer I) => void ? I : never;
414type ExcludeFromTuple<T, E, Acc extends unknown[] = []> = T extends [
415 infer Head,
416 ...infer Tail
417] ? ExcludeFromTuple<Tail, E, [...Acc, ...([Head] extends [E] ? [] : [Head])]> : Acc;
418type 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;
419type ExtractDispatchExtensions<M> = M extends Tuple<infer MiddlewareTuple> ? ExtractDispatchFromMiddlewareTuple<MiddlewareTuple, {}> : M extends ReadonlyArray<Middleware> ? ExtractDispatchFromMiddlewareTuple<[...M], {}> : never;
420type 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;
421type 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;
422type 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;
423type 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 */
431type NoInfer<T> = [T][T extends any ? 0 : never];
432type NonUndefined<T> = T extends undefined ? never : T;
433type WithRequiredProp<T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>;
434type WithOptionalProp<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
435interface TypeGuard<T> {
436 (value: any): value is T;
437}
438interface HasMatchFunction<T> {
439 match: TypeGuard<T>;
440}
441/** @public */
442type Matcher<T> = HasMatchFunction<T> | TypeGuard<T>;
443/** @public */
444type ActionFromMatcher<M extends Matcher<any>> = M extends Matcher<infer T> ? T : never;
445type Id<T> = {
446 [K in keyof T]: T[K];
447} & {};
448type Tail<T extends any[]> = T extends [any, ...infer Tail] ? Tail : never;
449type 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 */
454type SafePromise<T> = Promise<T> & {
455 __linterBrands: 'SafePromise';
456};
457
458interface ThunkOptions<E = any> {
459 extraArgument: E;
460}
461interface GetDefaultMiddlewareOptions {
462 thunk?: boolean | ThunkOptions;
463 immutableCheck?: boolean | ImmutableStateInvariantMiddlewareOptions;
464 serializableCheck?: boolean | SerializableStateInvariantMiddlewareOptions;
465 actionCreatorCheck?: boolean | ActionCreatorInvariantMiddlewareOptions;
466}
467type 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>;
474type 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
481declare const SHOULD_AUTOBATCH = "RTK_autoBatch";
482declare const prepareAutoBatched: <T>() => (payload: T) => {
483 payload: T;
484 meta: unknown;
485};
486type 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 */
519declare const autoBatchEnhancer: (options?: AutoBatchOptions) => StoreEnhancer;
520
521type GetDefaultEnhancersOptions = {
522 autoBatch?: boolean | AutoBatchOptions;
523};
524type GetDefaultEnhancers<M extends Middlewares<any>> = (options?: GetDefaultEnhancersOptions) => Tuple<[StoreEnhancer<{
525 dispatch: ExtractDispatchExtensions<M>;
526}>]>;
527
528/**
529 * Options for `configureStore()`.
530 *
531 * @public
532 */
533interface 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 * Whether to check for duplicate middleware instances. Defaults to `true`.
555 */
556 duplicateMiddlewareCheck?: boolean;
557 /**
558 * The initial state, same as Redux's createStore.
559 * You may optionally specify it to hydrate the state
560 * from the server in universal apps, or to restore a previously serialized
561 * user session. If you use `combineReducers()` to produce the root reducer
562 * function (either directly or indirectly by passing an object as `reducer`),
563 * this must be an object with the same shape as the reducer map keys.
564 */
565 preloadedState?: P;
566 /**
567 * The store enhancers to apply. See Redux's `createStore()`.
568 * All enhancers will be included before the DevTools Extension enhancer.
569 * If you need to customize the order of enhancers, supply a callback
570 * function that will receive a `getDefaultEnhancers` function that returns a Tuple,
571 * and should return a Tuple of enhancers (such as `getDefaultEnhancers().concat(offline)`).
572 * If you only need to add middleware, you can use the `middleware` parameter instead.
573 */
574 enhancers?: (getDefaultEnhancers: GetDefaultEnhancers<M>) => E;
575}
576type Middlewares<S> = ReadonlyArray<Middleware<{}, S>>;
577type Enhancers = ReadonlyArray<StoreEnhancer>;
578/**
579 * A Redux store returned by `configureStore()`. Supports dispatching
580 * side-effectful _thunks_ in addition to plain actions.
581 *
582 * @public
583 */
584type EnhancedStore<S = any, A extends Action = UnknownAction, E extends Enhancers = Enhancers> = ExtractStoreExtensions<E> & Store<S, A, UnknownIfNonSpecific<ExtractStateExtensions<E>>>;
585/**
586 * A friendly abstraction over the standard Redux `createStore()` function.
587 *
588 * @param options The store configuration.
589 * @returns A configured Redux store.
590 *
591 * @public
592 */
593declare function configureStore<S = any, A extends Action = UnknownAction, M extends Tuple<Middlewares<S>> = Tuple<[ThunkMiddlewareFor<S>]>, E extends Tuple<Enhancers> = Tuple<[
594 StoreEnhancer<{
595 dispatch: ExtractDispatchExtensions<M>;
596 }>,
597 StoreEnhancer
598]>, P = S>(options: ConfigureStoreOptions<S, A, M, E, P>): EnhancedStore<S, A, E>;
599
600/**
601 * An action with a string type and an associated payload. This is the
602 * type of action returned by `createAction()` action creators.
603 *
604 * @template P The type of the action's payload.
605 * @template T the type used for the action type.
606 * @template M The type of the action's meta (optional)
607 * @template E The type of the action's error (optional)
608 *
609 * @public
610 */
611type PayloadAction<P = void, T extends string = string, M = never, E = never> = {
612 payload: P;
613 type: T;
614} & ([M] extends [never] ? {} : {
615 meta: M;
616}) & ([E] extends [never] ? {} : {
617 error: E;
618});
619/**
620 * A "prepare" method to be used as the second parameter of `createAction`.
621 * Takes any number of arguments and returns a Flux Standard Action without
622 * type (will be added later) that *must* contain a payload (might be undefined).
623 *
624 * @public
625 */
626type PrepareAction<P> = ((...args: any[]) => {
627 payload: P;
628}) | ((...args: any[]) => {
629 payload: P;
630 meta: any;
631}) | ((...args: any[]) => {
632 payload: P;
633 error: any;
634}) | ((...args: any[]) => {
635 payload: P;
636 meta: any;
637 error: any;
638});
639/**
640 * Internal version of `ActionCreatorWithPreparedPayload`. Not to be used externally.
641 *
642 * @internal
643 */
644type _ActionCreatorWithPreparedPayload<PA extends PrepareAction<any> | void, T extends string = string> = PA extends PrepareAction<infer P> ? ActionCreatorWithPreparedPayload<Parameters<PA>, P, T, ReturnType<PA> extends {
645 error: infer E;
646} ? E : never, ReturnType<PA> extends {
647 meta: infer M;
648} ? M : never> : void;
649/**
650 * Basic type for all action creators.
651 *
652 * @inheritdoc {redux#ActionCreator}
653 */
654type BaseActionCreator<P, T extends string, M = never, E = never> = {
655 type: T;
656 match: (action: unknown) => action is PayloadAction<P, T, M, E>;
657};
658/**
659 * An action creator that takes multiple arguments that are passed
660 * to a `PrepareAction` method to create the final Action.
661 * @typeParam Args arguments for the action creator function
662 * @typeParam P `payload` type
663 * @typeParam T `type` name
664 * @typeParam E optional `error` type
665 * @typeParam M optional `meta` type
666 *
667 * @inheritdoc {redux#ActionCreator}
668 *
669 * @public
670 */
671interface ActionCreatorWithPreparedPayload<Args extends unknown[], P, T extends string = string, E = never, M = never> extends BaseActionCreator<P, T, M, E> {
672 /**
673 * Calling this {@link redux#ActionCreator} with `Args` will return
674 * an Action with a payload of type `P` and (depending on the `PrepareAction`
675 * method used) a `meta`- and `error` property of types `M` and `E` respectively.
676 */
677 (...args: Args): PayloadAction<P, T, M, E>;
678}
679/**
680 * An action creator of type `T` that takes an optional payload of type `P`.
681 *
682 * @inheritdoc {redux#ActionCreator}
683 *
684 * @public
685 */
686interface ActionCreatorWithOptionalPayload<P, T extends string = string> extends BaseActionCreator<P, T> {
687 /**
688 * Calling this {@link redux#ActionCreator} with an argument will
689 * return a {@link PayloadAction} of type `T` with a payload of `P`.
690 * Calling it without an argument will return a PayloadAction with a payload of `undefined`.
691 */
692 (payload?: P): PayloadAction<P, T>;
693}
694/**
695 * An action creator of type `T` that takes no payload.
696 *
697 * @inheritdoc {redux#ActionCreator}
698 *
699 * @public
700 */
701interface ActionCreatorWithoutPayload<T extends string = string> extends BaseActionCreator<undefined, T> {
702 /**
703 * Calling this {@link redux#ActionCreator} will
704 * return a {@link PayloadAction} of type `T` with a payload of `undefined`
705 */
706 (noArgument: void): PayloadAction<undefined, T>;
707}
708/**
709 * An action creator of type `T` that requires a payload of type P.
710 *
711 * @inheritdoc {redux#ActionCreator}
712 *
713 * @public
714 */
715interface ActionCreatorWithPayload<P, T extends string = string> extends BaseActionCreator<P, T> {
716 /**
717 * Calling this {@link redux#ActionCreator} with an argument will
718 * return a {@link PayloadAction} of type `T` with a payload of `P`
719 */
720 (payload: P): PayloadAction<P, T>;
721}
722/**
723 * An action creator of type `T` whose `payload` type could not be inferred. Accepts everything as `payload`.
724 *
725 * @inheritdoc {redux#ActionCreator}
726 *
727 * @public
728 */
729interface ActionCreatorWithNonInferrablePayload<T extends string = string> extends BaseActionCreator<unknown, T> {
730 /**
731 * Calling this {@link redux#ActionCreator} with an argument will
732 * return a {@link PayloadAction} of type `T` with a payload
733 * of exactly the type of the argument.
734 */
735 <PT extends unknown>(payload: PT): PayloadAction<PT, T>;
736}
737/**
738 * An action creator that produces actions with a `payload` attribute.
739 *
740 * @typeParam P the `payload` type
741 * @typeParam T the `type` of the resulting action
742 * @typeParam PA if the resulting action is preprocessed by a `prepare` method, the signature of said method.
743 *
744 * @public
745 */
746type 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>>>>>>;
747/**
748 * A utility function to create an action creator for the given action type
749 * string. The action creator accepts a single argument, which will be included
750 * in the action object as a field called payload. The action creator function
751 * will also have its toString() overridden so that it returns the action type.
752 *
753 * @param type The action type to use for created actions.
754 * @param prepare (optional) a method that takes any number of arguments and returns { payload } or { payload, meta }.
755 * If this is given, the resulting action creator will pass its arguments to this method to calculate payload & meta.
756 *
757 * @public
758 */
759declare function createAction<P = void, T extends string = string>(type: T): PayloadActionCreator<P, T>;
760/**
761 * A utility function to create an action creator for the given action type
762 * string. The action creator accepts a single argument, which will be included
763 * in the action object as a field called payload. The action creator function
764 * will also have its toString() overridden so that it returns the action type.
765 *
766 * @param type The action type to use for created actions.
767 * @param prepare (optional) a method that takes any number of arguments and returns { payload } or { payload, meta }.
768 * If this is given, the resulting action creator will pass its arguments to this method to calculate payload & meta.
769 *
770 * @public
771 */
772declare function createAction<PA extends PrepareAction<any>, T extends string = string>(type: T, prepareAction: PA): PayloadActionCreator<ReturnType<PA>['payload'], T, PA>;
773/**
774 * Returns true if value is an RTK-like action creator, with a static type property and match method.
775 */
776declare function isActionCreator(action: unknown): action is BaseActionCreator<unknown, string> & Function;
777/**
778 * Returns true if value is an action with a string type and valid Flux Standard Action keys.
779 */
780declare function isFSA(action: unknown): action is {
781 type: string;
782 payload?: unknown;
783 error?: unknown;
784 meta?: unknown;
785};
786type IfPrepareActionMethodProvided<PA extends PrepareAction<any> | void, True, False> = PA extends (...args: any[]) => any ? True : False;
787
788type BaseThunkAPI<S, E, D extends Dispatch = Dispatch, RejectedValue = unknown, RejectedMeta = unknown, FulfilledMeta = unknown> = {
789 dispatch: D;
790 getState: () => S;
791 extra: E;
792 requestId: string;
793 signal: AbortSignal;
794 abort: (reason?: string) => void;
795 rejectWithValue: IsUnknown<RejectedMeta, (value: RejectedValue) => RejectWithValue<RejectedValue, RejectedMeta>, (value: RejectedValue, meta: RejectedMeta) => RejectWithValue<RejectedValue, RejectedMeta>>;
796 fulfillWithValue: IsUnknown<FulfilledMeta, <FulfilledValue>(value: FulfilledValue) => FulfilledValue, <FulfilledValue>(value: FulfilledValue, meta: FulfilledMeta) => FulfillWithMeta<FulfilledValue, FulfilledMeta>>;
797};
798/**
799 * @public
800 */
801interface SerializedError {
802 name?: string;
803 message?: string;
804 stack?: string;
805 code?: string;
806}
807declare class RejectWithValue<Payload, RejectedMeta> {
808 readonly payload: Payload;
809 readonly meta: RejectedMeta;
810 private readonly _type;
811 constructor(payload: Payload, meta: RejectedMeta);
812}
813declare class FulfillWithMeta<Payload, FulfilledMeta> {
814 readonly payload: Payload;
815 readonly meta: FulfilledMeta;
816 private readonly _type;
817 constructor(payload: Payload, meta: FulfilledMeta);
818}
819/**
820 * Serializes an error into a plain object.
821 * Reworked from https://github.com/sindresorhus/serialize-error
822 *
823 * @public
824 */
825declare const miniSerializeError: (value: any) => SerializedError;
826type AsyncThunkConfig = {
827 state?: unknown;
828 dispatch?: ThunkDispatch<unknown, unknown, UnknownAction>;
829 extra?: unknown;
830 rejectValue?: unknown;
831 serializedErrorType?: unknown;
832 pendingMeta?: unknown;
833 fulfilledMeta?: unknown;
834 rejectedMeta?: unknown;
835};
836type GetState<ThunkApiConfig> = ThunkApiConfig extends {
837 state: infer State;
838} ? State : unknown;
839type GetExtra<ThunkApiConfig> = ThunkApiConfig extends {
840 extra: infer Extra;
841} ? Extra : unknown;
842type GetDispatch<ThunkApiConfig> = ThunkApiConfig extends {
843 dispatch: infer Dispatch;
844} ? FallbackIfUnknown<Dispatch, ThunkDispatch<GetState<ThunkApiConfig>, GetExtra<ThunkApiConfig>, UnknownAction>> : ThunkDispatch<GetState<ThunkApiConfig>, GetExtra<ThunkApiConfig>, UnknownAction>;
845type GetThunkAPI<ThunkApiConfig> = BaseThunkAPI<GetState<ThunkApiConfig>, GetExtra<ThunkApiConfig>, GetDispatch<ThunkApiConfig>, GetRejectValue<ThunkApiConfig>, GetRejectedMeta<ThunkApiConfig>, GetFulfilledMeta<ThunkApiConfig>>;
846type GetRejectValue<ThunkApiConfig> = ThunkApiConfig extends {
847 rejectValue: infer RejectValue;
848} ? RejectValue : unknown;
849type GetPendingMeta<ThunkApiConfig> = ThunkApiConfig extends {
850 pendingMeta: infer PendingMeta;
851} ? PendingMeta : unknown;
852type GetFulfilledMeta<ThunkApiConfig> = ThunkApiConfig extends {
853 fulfilledMeta: infer FulfilledMeta;
854} ? FulfilledMeta : unknown;
855type GetRejectedMeta<ThunkApiConfig> = ThunkApiConfig extends {
856 rejectedMeta: infer RejectedMeta;
857} ? RejectedMeta : unknown;
858type GetSerializedErrorType<ThunkApiConfig> = ThunkApiConfig extends {
859 serializedErrorType: infer GetSerializedErrorType;
860} ? GetSerializedErrorType : SerializedError;
861type MaybePromise<T> = T | Promise<T> | (T extends any ? Promise<T> : never);
862/**
863 * A type describing the return value of the `payloadCreator` argument to `createAsyncThunk`.
864 * Might be useful for wrapping `createAsyncThunk` in custom abstractions.
865 *
866 * @public
867 */
868type AsyncThunkPayloadCreatorReturnValue<Returned, ThunkApiConfig extends AsyncThunkConfig> = MaybePromise<IsUnknown<GetFulfilledMeta<ThunkApiConfig>, Returned, FulfillWithMeta<Returned, GetFulfilledMeta<ThunkApiConfig>>> | RejectWithValue<GetRejectValue<ThunkApiConfig>, GetRejectedMeta<ThunkApiConfig>>>;
869/**
870 * A type describing the `payloadCreator` argument to `createAsyncThunk`.
871 * Might be useful for wrapping `createAsyncThunk` in custom abstractions.
872 *
873 * @public
874 */
875type AsyncThunkPayloadCreator<Returned, ThunkArg = void, ThunkApiConfig extends AsyncThunkConfig = {}> = (arg: ThunkArg, thunkAPI: GetThunkAPI<ThunkApiConfig>) => AsyncThunkPayloadCreatorReturnValue<Returned, ThunkApiConfig>;
876/**
877 * A ThunkAction created by `createAsyncThunk`.
878 * Dispatching it returns a Promise for either a
879 * fulfilled or rejected action.
880 * Also, the returned value contains an `abort()` method
881 * that allows the asyncAction to be cancelled from the outside.
882 *
883 * @public
884 */
885type 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>>> & {
886 abort: (reason?: string) => void;
887 requestId: string;
888 arg: ThunkArg;
889 unwrap: () => Promise<Returned>;
890};
891/**
892 * Config provided when calling the async thunk action creator.
893 */
894interface AsyncThunkDispatchConfig {
895 /**
896 * An external `AbortSignal` that will be tracked by the internal `AbortSignal`.
897 */
898 signal?: AbortSignal;
899}
900type 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>>;
901/**
902 * Options object for `createAsyncThunk`.
903 *
904 * @public
905 */
906type AsyncThunkOptions<ThunkArg = void, ThunkApiConfig extends AsyncThunkConfig = {}> = {
907 /**
908 * A method to control whether the asyncThunk should be executed. Has access to the
909 * `arg`, `api.getState()` and `api.extra` arguments.
910 *
911 * @returns `false` if it should be skipped
912 */
913 condition?(arg: ThunkArg, api: Pick<GetThunkAPI<ThunkApiConfig>, 'getState' | 'extra'>): MaybePromise<boolean | undefined>;
914 /**
915 * If `condition` returns `false`, the asyncThunk will be skipped.
916 * This option allows you to control whether a `rejected` action with `meta.condition == false`
917 * will be dispatched or not.
918 *
919 * @default `false`
920 */
921 dispatchConditionRejection?: boolean;
922 serializeError?: (x: unknown) => GetSerializedErrorType<ThunkApiConfig>;
923 /**
924 * A function to use when generating the `requestId` for the request sequence.
925 *
926 * @default `nanoid`
927 */
928 idGenerator?: (arg: ThunkArg) => string;
929} & IsUnknown<GetPendingMeta<ThunkApiConfig>, {
930 /**
931 * A method to generate additional properties to be added to `meta` of the pending action.
932 *
933 * Using this optional overload will not modify the types correctly, this overload is only in place to support JavaScript users.
934 * Please use the `ThunkApiConfig` parameter `pendingMeta` to get access to a correctly typed overload
935 */
936 getPendingMeta?(base: {
937 arg: ThunkArg;
938 requestId: string;
939 }, api: Pick<GetThunkAPI<ThunkApiConfig>, 'getState' | 'extra'>): GetPendingMeta<ThunkApiConfig>;
940}, {
941 /**
942 * A method to generate additional properties to be added to `meta` of the pending action.
943 */
944 getPendingMeta(base: {
945 arg: ThunkArg;
946 requestId: string;
947 }, api: Pick<GetThunkAPI<ThunkApiConfig>, 'getState' | 'extra'>): GetPendingMeta<ThunkApiConfig>;
948}>;
949type AsyncThunkPendingActionCreator<ThunkArg, ThunkApiConfig = {}> = ActionCreatorWithPreparedPayload<[
950 string,
951 ThunkArg,
952 GetPendingMeta<ThunkApiConfig>?
953], undefined, string, never, {
954 arg: ThunkArg;
955 requestId: string;
956 requestStatus: 'pending';
957} & GetPendingMeta<ThunkApiConfig>>;
958type AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig = {}> = ActionCreatorWithPreparedPayload<[
959 Error | null,
960 string,
961 ThunkArg,
962 GetRejectValue<ThunkApiConfig>?,
963 GetRejectedMeta<ThunkApiConfig>?
964], GetRejectValue<ThunkApiConfig> | undefined, string, GetSerializedErrorType<ThunkApiConfig>, {
965 arg: ThunkArg;
966 requestId: string;
967 requestStatus: 'rejected';
968 aborted: boolean;
969 condition: boolean;
970} & (({
971 rejectedWithValue: false;
972} & {
973 [K in keyof GetRejectedMeta<ThunkApiConfig>]?: undefined;
974}) | ({
975 rejectedWithValue: true;
976} & GetRejectedMeta<ThunkApiConfig>))>;
977type AsyncThunkFulfilledActionCreator<Returned, ThunkArg, ThunkApiConfig = {}> = ActionCreatorWithPreparedPayload<[
978 Returned,
979 string,
980 ThunkArg,
981 GetFulfilledMeta<ThunkApiConfig>?
982], Returned, string, never, {
983 arg: ThunkArg;
984 requestId: string;
985 requestStatus: 'fulfilled';
986} & GetFulfilledMeta<ThunkApiConfig>>;
987/**
988 * A type describing the return value of `createAsyncThunk`.
989 * Might be useful for wrapping `createAsyncThunk` in custom abstractions.
990 *
991 * @public
992 */
993type AsyncThunk<Returned, ThunkArg, ThunkApiConfig extends AsyncThunkConfig> = AsyncThunkActionCreator<Returned, ThunkArg, ThunkApiConfig> & {
994 pending: AsyncThunkPendingActionCreator<ThunkArg, ThunkApiConfig>;
995 rejected: AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig>;
996 fulfilled: AsyncThunkFulfilledActionCreator<Returned, ThunkArg, ThunkApiConfig>;
997 settled: (action: any) => action is ReturnType<AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig> | AsyncThunkFulfilledActionCreator<Returned, ThunkArg, ThunkApiConfig>>;
998 typePrefix: string;
999};
1000type OverrideThunkApiConfigs<OldConfig, NewConfig> = Id<NewConfig & Omit<OldConfig, keyof NewConfig>>;
1001type CreateAsyncThunkFunction<CurriedThunkApiConfig extends AsyncThunkConfig> = {
1002 /**
1003 *
1004 * @param typePrefix
1005 * @param payloadCreator
1006 * @param options
1007 *
1008 * @public
1009 */
1010 <Returned, ThunkArg = void>(typePrefix: string, payloadCreator: AsyncThunkPayloadCreator<Returned, ThunkArg, CurriedThunkApiConfig>, options?: AsyncThunkOptions<ThunkArg, CurriedThunkApiConfig>): AsyncThunk<Returned, ThunkArg, CurriedThunkApiConfig>;
1011 /**
1012 *
1013 * @param typePrefix
1014 * @param payloadCreator
1015 * @param options
1016 *
1017 * @public
1018 */
1019 <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>>;
1020};
1021type CreateAsyncThunk<CurriedThunkApiConfig extends AsyncThunkConfig> = CreateAsyncThunkFunction<CurriedThunkApiConfig> & {
1022 withTypes<ThunkApiConfig extends AsyncThunkConfig>(): CreateAsyncThunk<OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>>;
1023};
1024declare const createAsyncThunk: CreateAsyncThunk<AsyncThunkConfig>;
1025interface UnwrappableAction {
1026 payload: any;
1027 meta?: any;
1028 error?: any;
1029}
1030type UnwrappedActionPayload<T extends UnwrappableAction> = Exclude<T, {
1031 error: any;
1032}>['payload'];
1033/**
1034 * @public
1035 */
1036declare function unwrapResult<R extends UnwrappableAction>(action: R): UnwrappedActionPayload<R>;
1037type WithStrictNullChecks<True, False> = undefined extends boolean ? False : True;
1038
1039type AsyncThunkReducers<State, ThunkArg extends any, Returned = unknown, ThunkApiConfig extends AsyncThunkConfig = {}> = {
1040 pending?: CaseReducer<State, ReturnType<AsyncThunk<Returned, ThunkArg, ThunkApiConfig>['pending']>>;
1041 rejected?: CaseReducer<State, ReturnType<AsyncThunk<Returned, ThunkArg, ThunkApiConfig>['rejected']>>;
1042 fulfilled?: CaseReducer<State, ReturnType<AsyncThunk<Returned, ThunkArg, ThunkApiConfig>['fulfilled']>>;
1043 settled?: CaseReducer<State, ReturnType<AsyncThunk<Returned, ThunkArg, ThunkApiConfig>['rejected' | 'fulfilled']>>;
1044};
1045type TypedActionCreator<Type extends string> = {
1046 (...args: any[]): Action<Type>;
1047 type: Type;
1048};
1049/**
1050 * A builder for an action <-> reducer map.
1051 *
1052 * @public
1053 */
1054interface ActionReducerMapBuilder<State> {
1055 /**
1056 * Adds a case reducer to handle a single exact action type.
1057 * @remarks
1058 * All calls to `builder.addCase` must come before any calls to `builder.addMatcher` or `builder.addDefaultCase`.
1059 * @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.
1060 * @param reducer - The actual case reducer function.
1061 */
1062 addCase<ActionCreator extends TypedActionCreator<string>>(actionCreator: ActionCreator, reducer: CaseReducer<State, ReturnType<ActionCreator>>): ActionReducerMapBuilder<State>;
1063 /**
1064 * Adds a case reducer to handle a single exact action type.
1065 * @remarks
1066 * All calls to `builder.addCase` must come before any calls to `builder.addAsyncThunk`, `builder.addMatcher` or `builder.addDefaultCase`.
1067 * @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.
1068 * @param reducer - The actual case reducer function.
1069 */
1070 addCase<Type extends string, A extends Action<Type>>(type: Type, reducer: CaseReducer<State, A>): ActionReducerMapBuilder<State>;
1071 /**
1072 * Adds case reducers to handle actions based on a `AsyncThunk` action creator.
1073 * @remarks
1074 * All calls to `builder.addAsyncThunk` must come before after any calls to `builder.addCase` and before any calls to `builder.addMatcher` or `builder.addDefaultCase`.
1075 * @param asyncThunk - The async thunk action creator itself.
1076 * @param reducers - A mapping from each of the `AsyncThunk` action types to the case reducer that should handle those actions.
1077 * @example
1078 ```ts no-transpile
1079 import { createAsyncThunk, createReducer } from '@reduxjs/toolkit'
1080
1081 const fetchUserById = createAsyncThunk('users/fetchUser', async (id) => {
1082 const response = await fetch(`https://reqres.in/api/users/${id}`)
1083 return (await response.json()).data
1084 })
1085
1086 const reducer = createReducer(initialState, (builder) => {
1087 builder.addAsyncThunk(fetchUserById, {
1088 pending: (state, action) => {
1089 state.fetchUserById.loading = 'pending'
1090 },
1091 fulfilled: (state, action) => {
1092 state.fetchUserById.data = action.payload
1093 },
1094 rejected: (state, action) => {
1095 state.fetchUserById.error = action.error
1096 },
1097 settled: (state, action) => {
1098 state.fetchUserById.loading = action.meta.requestStatus
1099 },
1100 })
1101 })
1102 */
1103 addAsyncThunk<Returned, ThunkArg, ThunkApiConfig extends AsyncThunkConfig = {}>(asyncThunk: AsyncThunk<Returned, ThunkArg, ThunkApiConfig>, reducers: AsyncThunkReducers<State, ThunkArg, Returned, ThunkApiConfig>): Omit<ActionReducerMapBuilder<State>, 'addCase'>;
1104 /**
1105 * Allows you to match your incoming actions against your own filter function instead of only the `action.type` property.
1106 * @remarks
1107 * If multiple matcher reducers match, all of them will be executed in the order
1108 * they were defined in - even if a case reducer already matched.
1109 * All calls to `builder.addMatcher` must come after any calls to `builder.addCase` and `builder.addAsyncThunk` and before any calls to `builder.addDefaultCase`.
1110 * @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)
1111 * function
1112 * @param reducer - The actual case reducer function.
1113 *
1114 * @example
1115 ```ts
1116 import {
1117 createAction,
1118 createReducer,
1119 AsyncThunk,
1120 UnknownAction,
1121 } from "@reduxjs/toolkit";
1122
1123 type GenericAsyncThunk = AsyncThunk<unknown, unknown, any>;
1124
1125 type PendingAction = ReturnType<GenericAsyncThunk["pending"]>;
1126 type RejectedAction = ReturnType<GenericAsyncThunk["rejected"]>;
1127 type FulfilledAction = ReturnType<GenericAsyncThunk["fulfilled"]>;
1128
1129 const initialState: Record<string, string> = {};
1130 const resetAction = createAction("reset-tracked-loading-state");
1131
1132 function isPendingAction(action: UnknownAction): action is PendingAction {
1133 return typeof action.type === "string" && action.type.endsWith("/pending");
1134 }
1135
1136 const reducer = createReducer(initialState, (builder) => {
1137 builder
1138 .addCase(resetAction, () => initialState)
1139 // matcher can be defined outside as a type predicate function
1140 .addMatcher(isPendingAction, (state, action) => {
1141 state[action.meta.requestId] = "pending";
1142 })
1143 .addMatcher(
1144 // matcher can be defined inline as a type predicate function
1145 (action): action is RejectedAction => action.type.endsWith("/rejected"),
1146 (state, action) => {
1147 state[action.meta.requestId] = "rejected";
1148 }
1149 )
1150 // matcher can just return boolean and the matcher can receive a generic argument
1151 .addMatcher<FulfilledAction>(
1152 (action) => action.type.endsWith("/fulfilled"),
1153 (state, action) => {
1154 state[action.meta.requestId] = "fulfilled";
1155 }
1156 );
1157 });
1158 ```
1159 */
1160 addMatcher<A>(matcher: TypeGuard<A> | ((action: any) => boolean), reducer: CaseReducer<State, A extends Action ? A : A & Action>): Omit<ActionReducerMapBuilder<State>, 'addCase' | 'addAsyncThunk'>;
1161 /**
1162 * Adds a "default case" reducer that is executed if no case reducer and no matcher
1163 * reducer was executed for this action.
1164 * @param reducer - The fallback "default case" reducer function.
1165 *
1166 * @example
1167 ```ts
1168 import { createReducer } from '@reduxjs/toolkit'
1169 const initialState = { otherActions: 0 }
1170 const reducer = createReducer(initialState, builder => {
1171 builder
1172 // .addCase(...)
1173 // .addMatcher(...)
1174 .addDefaultCase((state, action) => {
1175 state.otherActions++
1176 })
1177 })
1178 ```
1179 */
1180 addDefaultCase(reducer: CaseReducer<State, Action>): {};
1181}
1182
1183/**
1184 * Defines a mapping from action types to corresponding action object shapes.
1185 *
1186 * @deprecated This should not be used manually - it is only used for internal
1187 * inference purposes and should not have any further value.
1188 * It might be removed in the future.
1189 * @public
1190 */
1191type Actions<T extends keyof any = string> = Record<T, Action>;
1192/**
1193 * A *case reducer* is a reducer function for a specific action type. Case
1194 * reducers can be composed to full reducers using `createReducer()`.
1195 *
1196 * Unlike a normal Redux reducer, a case reducer is never called with an
1197 * `undefined` state to determine the initial state. Instead, the initial
1198 * state is explicitly specified as an argument to `createReducer()`.
1199 *
1200 * In addition, a case reducer can choose to mutate the passed-in `state`
1201 * value directly instead of returning a new state. This does not actually
1202 * cause the store state to be mutated directly; instead, thanks to
1203 * [immer](https://github.com/mweststrate/immer), the mutations are
1204 * translated to copy operations that result in a new state.
1205 *
1206 * @public
1207 */
1208type CaseReducer<S = any, A extends Action = UnknownAction> = (state: Draft<S>, action: A) => NoInfer<S> | void | Draft<NoInfer<S>>;
1209/**
1210 * A mapping from action types to case reducers for `createReducer()`.
1211 *
1212 * @deprecated This should not be used manually - it is only used
1213 * for internal inference purposes and using it manually
1214 * would lead to type erasure.
1215 * It might be removed in the future.
1216 * @public
1217 */
1218type CaseReducers<S, AS extends Actions> = {
1219 [T in keyof AS]: AS[T] extends Action ? CaseReducer<S, AS[T]> : void;
1220};
1221type NotFunction<T> = T extends Function ? never : T;
1222type ReducerWithInitialState<S extends NotFunction<any>> = Reducer<S> & {
1223 getInitialState: () => S;
1224};
1225/**
1226 * A utility function that allows defining a reducer as a mapping from action
1227 * type to *case reducer* functions that handle these action types. The
1228 * reducer's initial state is passed as the first argument.
1229 *
1230 * @remarks
1231 * The body of every case reducer is implicitly wrapped with a call to
1232 * `produce()` from the [immer](https://github.com/mweststrate/immer) library.
1233 * This means that rather than returning a new state object, you can also
1234 * mutate the passed-in state object directly; these mutations will then be
1235 * automatically and efficiently translated into copies, giving you both
1236 * convenience and immutability.
1237 *
1238 * @overloadSummary
1239 * This function accepts a callback that receives a `builder` object as its argument.
1240 * That builder provides `addCase`, `addMatcher` and `addDefaultCase` functions that may be
1241 * called to define what actions this reducer will handle.
1242 *
1243 * @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`.
1244 * @param builderCallback - `(builder: Builder) => void` A callback that receives a *builder* object to define
1245 * case reducers via calls to `builder.addCase(actionCreatorOrType, reducer)`.
1246 * @example
1247```ts
1248import {
1249 createAction,
1250 createReducer,
1251 UnknownAction,
1252 PayloadAction,
1253} from "@reduxjs/toolkit";
1254
1255const increment = createAction<number>("increment");
1256const decrement = createAction<number>("decrement");
1257
1258function isActionWithNumberPayload(
1259 action: UnknownAction
1260): action is PayloadAction<number> {
1261 return typeof action.payload === "number";
1262}
1263
1264const reducer = createReducer(
1265 {
1266 counter: 0,
1267 sumOfNumberPayloads: 0,
1268 unhandledActions: 0,
1269 },
1270 (builder) => {
1271 builder
1272 .addCase(increment, (state, action) => {
1273 // action is inferred correctly here
1274 state.counter += action.payload;
1275 })
1276 // You can chain calls, or have separate `builder.addCase()` lines each time
1277 .addCase(decrement, (state, action) => {
1278 state.counter -= action.payload;
1279 })
1280 // You can apply a "matcher function" to incoming actions
1281 .addMatcher(isActionWithNumberPayload, (state, action) => {})
1282 // and provide a default case if no other handlers matched
1283 .addDefaultCase((state, action) => {});
1284 }
1285);
1286```
1287 * @public
1288 */
1289declare function createReducer<S extends NotFunction<any>>(initialState: S | (() => S), mapOrBuilderCallback: (builder: ActionReducerMapBuilder<S>) => void): ReducerWithInitialState<S>;
1290
1291type SliceLike<ReducerPath extends string, State, PreloadedState = State> = {
1292 reducerPath: ReducerPath;
1293 reducer: Reducer<State, any, PreloadedState>;
1294};
1295type AnySliceLike = SliceLike<string, any>;
1296type SliceLikeReducerPath<A extends AnySliceLike> = A extends SliceLike<infer ReducerPath, any> ? ReducerPath : never;
1297type SliceLikeState<A extends AnySliceLike> = A extends SliceLike<any, infer State, any> ? State : never;
1298type SliceLikePreloadedState<A extends AnySliceLike> = A extends SliceLike<any, any, infer PreloadedState> ? PreloadedState : never;
1299type WithSlice<A extends AnySliceLike> = {
1300 [Path in SliceLikeReducerPath<A>]: SliceLikeState<A>;
1301};
1302type WithSlicePreloadedState<A extends AnySliceLike> = {
1303 [Path in SliceLikeReducerPath<A>]: SliceLikePreloadedState<A>;
1304};
1305type ReducerMap = Record<string, Reducer>;
1306type ExistingSliceLike<DeclaredState, PreloadedState> = {
1307 [ReducerPath in keyof DeclaredState]: SliceLike<ReducerPath & string, NonUndefined<DeclaredState[ReducerPath]>, NonUndefined<PreloadedState[ReducerPath & keyof PreloadedState]>>;
1308}[keyof DeclaredState];
1309type InjectConfig = {
1310 /**
1311 * 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.
1312 */
1313 overrideExisting?: boolean;
1314};
1315/**
1316 * A reducer that allows for slices/reducers to be injected after initialisation.
1317 */
1318interface CombinedSliceReducer<InitialState, DeclaredState extends InitialState = InitialState, PreloadedState extends Partial<Record<keyof PreloadedState, any>> = Partial<DeclaredState>> extends Reducer<DeclaredState, UnknownAction, PreloadedState> {
1319 /**
1320 * Provide a type for slices that will be injected lazily.
1321 *
1322 * One way to do this would be with interface merging:
1323 * ```ts
1324 *
1325 * export interface LazyLoadedSlices {}
1326 *
1327 * export const rootReducer = combineSlices(stringSlice).withLazyLoadedSlices<LazyLoadedSlices>();
1328 *
1329 * // elsewhere
1330 *
1331 * declare module './reducer' {
1332 * export interface LazyLoadedSlices extends WithSlice<typeof booleanSlice> {}
1333 * }
1334 *
1335 * const withBoolean = rootReducer.inject(booleanSlice);
1336 *
1337 * // elsewhere again
1338 *
1339 * declare module './reducer' {
1340 * export interface LazyLoadedSlices {
1341 * customName: CustomState
1342 * }
1343 * }
1344 *
1345 * const withCustom = rootReducer.inject({ reducerPath: "customName", reducer: customSlice.reducer })
1346 * ```
1347 */
1348 withLazyLoadedSlices<Lazy = {}, LazyPreloaded = Lazy>(): CombinedSliceReducer<InitialState, Id<DeclaredState & Partial<Lazy>>, Id<PreloadedState & Partial<LazyPreloaded>>>;
1349 /**
1350 * Inject a slice.
1351 *
1352 * Accepts an individual slice, RTKQ API instance, or a "slice-like" { reducerPath, reducer } object.
1353 *
1354 * ```ts
1355 * rootReducer.inject(booleanSlice)
1356 * rootReducer.inject(baseApi)
1357 * rootReducer.inject({ reducerPath: 'boolean' as const, reducer: newReducer }, { overrideExisting: true })
1358 * ```
1359 *
1360 */
1361 inject<Sl extends Id<ExistingSliceLike<DeclaredState, PreloadedState>>>(slice: Sl, config?: InjectConfig): CombinedSliceReducer<InitialState, Id<DeclaredState & WithSlice<Sl>>, Id<PreloadedState & Partial<WithSlicePreloadedState<Sl>>>>;
1362 /**
1363 * Inject a slice.
1364 *
1365 * Accepts an individual slice, RTKQ API instance, or a "slice-like" { reducerPath, reducer } object.
1366 *
1367 * ```ts
1368 * rootReducer.inject(booleanSlice)
1369 * rootReducer.inject(baseApi)
1370 * rootReducer.inject({ reducerPath: 'boolean' as const, reducer: newReducer }, { overrideExisting: true })
1371 * ```
1372 *
1373 */
1374 inject<ReducerPath extends string, State, PreloadedState = State>(slice: SliceLike<ReducerPath, State & (ReducerPath extends keyof DeclaredState ? never : State), PreloadedState & (ReducerPath extends keyof PreloadedState ? never : PreloadedState)>, config?: InjectConfig): CombinedSliceReducer<InitialState, Id<DeclaredState & WithSlice<SliceLike<ReducerPath, State>>>, Id<PreloadedState & WithSlicePreloadedState<SliceLike<ReducerPath, State, PreloadedState>>>>;
1375 /**
1376 * Create a selector that guarantees that the slices injected will have a defined value when selector is run.
1377 *
1378 * ```ts
1379 * const selectBooleanWithoutInjection = (state: RootState) => state.boolean;
1380 * // ^? boolean | undefined
1381 *
1382 * const selectBoolean = rootReducer.inject(booleanSlice).selector((state) => {
1383 * // if action hasn't been dispatched since slice was injected, this would usually be undefined
1384 * // however selector() uses a Proxy around the first parameter to ensure that it evaluates to the initial state instead, if undefined
1385 * return state.boolean;
1386 * // ^? boolean
1387 * })
1388 * ```
1389 *
1390 * If the reducer is nested inside the root state, a selectState callback can be passed to retrieve the reducer's state.
1391 *
1392 * ```ts
1393 *
1394 * export interface LazyLoadedSlices {};
1395 *
1396 * export const innerReducer = combineSlices(stringSlice).withLazyLoadedSlices<LazyLoadedSlices>();
1397 *
1398 * export const rootReducer = combineSlices({ inner: innerReducer });
1399 *
1400 * export type RootState = ReturnType<typeof rootReducer>;
1401 *
1402 * // elsewhere
1403 *
1404 * declare module "./reducer.ts" {
1405 * export interface LazyLoadedSlices extends WithSlice<typeof booleanSlice> {}
1406 * }
1407 *
1408 * const withBool = innerReducer.inject(booleanSlice);
1409 *
1410 * const selectBoolean = withBool.selector(
1411 * (state) => state.boolean,
1412 * (rootState: RootState) => state.inner
1413 * );
1414 * // now expects to be passed RootState instead of innerReducer state
1415 *
1416 * ```
1417 *
1418 * Value passed to selectorFn will be a Proxy - use selector.original(proxy) to get original state value (useful for debugging)
1419 *
1420 * ```ts
1421 * const injectedReducer = rootReducer.inject(booleanSlice);
1422 * const selectBoolean = injectedReducer.selector((state) => {
1423 * console.log(injectedReducer.selector.original(state).boolean) // possibly undefined
1424 * return state.boolean
1425 * })
1426 * ```
1427 */
1428 selector: {
1429 /**
1430 * Create a selector that guarantees that the slices injected will have a defined value when selector is run.
1431 *
1432 * ```ts
1433 * const selectBooleanWithoutInjection = (state: RootState) => state.boolean;
1434 * // ^? boolean | undefined
1435 *
1436 * const selectBoolean = rootReducer.inject(booleanSlice).selector((state) => {
1437 * // if action hasn't been dispatched since slice was injected, this would usually be undefined
1438 * // however selector() uses a Proxy around the first parameter to ensure that it evaluates to the initial state instead, if undefined
1439 * return state.boolean;
1440 * // ^? boolean
1441 * })
1442 * ```
1443 *
1444 * Value passed to selectorFn will be a Proxy - use selector.original(proxy) to get original state value (useful for debugging)
1445 *
1446 * ```ts
1447 * const injectedReducer = rootReducer.inject(booleanSlice);
1448 * const selectBoolean = injectedReducer.selector((state) => {
1449 * console.log(injectedReducer.selector.original(state).boolean) // undefined
1450 * return state.boolean
1451 * })
1452 * ```
1453 */
1454 <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>;
1455 /**
1456 * Create a selector that guarantees that the slices injected will have a defined value when selector is run.
1457 *
1458 * ```ts
1459 * const selectBooleanWithoutInjection = (state: RootState) => state.boolean;
1460 * // ^? boolean | undefined
1461 *
1462 * const selectBoolean = rootReducer.inject(booleanSlice).selector((state) => {
1463 * // if action hasn't been dispatched since slice was injected, this would usually be undefined
1464 * // however selector() uses a Proxy around the first parameter to ensure that it evaluates to the initial state instead, if undefined
1465 * return state.boolean;
1466 * // ^? boolean
1467 * })
1468 * ```
1469 *
1470 * If the reducer is nested inside the root state, a selectState callback can be passed to retrieve the reducer's state.
1471 *
1472 * ```ts
1473 *
1474 * interface LazyLoadedSlices {};
1475 *
1476 * const innerReducer = combineSlices(stringSlice).withLazyLoadedSlices<LazyLoadedSlices>();
1477 *
1478 * const rootReducer = combineSlices({ inner: innerReducer });
1479 *
1480 * type RootState = ReturnType<typeof rootReducer>;
1481 *
1482 * // elsewhere
1483 *
1484 * declare module "./reducer.ts" {
1485 * interface LazyLoadedSlices extends WithSlice<typeof booleanSlice> {}
1486 * }
1487 *
1488 * const withBool = innerReducer.inject(booleanSlice);
1489 *
1490 * const selectBoolean = withBool.selector(
1491 * (state) => state.boolean,
1492 * (rootState: RootState) => state.inner
1493 * );
1494 * // now expects to be passed RootState instead of innerReducer state
1495 *
1496 * ```
1497 *
1498 * Value passed to selectorFn will be a Proxy - use selector.original(proxy) to get original state value (useful for debugging)
1499 *
1500 * ```ts
1501 * const injectedReducer = rootReducer.inject(booleanSlice);
1502 * const selectBoolean = injectedReducer.selector((state) => {
1503 * console.log(injectedReducer.selector.original(state).boolean) // possibly undefined
1504 * return state.boolean
1505 * })
1506 * ```
1507 */
1508 <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>;
1509 /**
1510 * Returns the unproxied state. Useful for debugging.
1511 * @param state state Proxy, that ensures injected reducers have value
1512 * @returns original, unproxied state
1513 * @throws if value passed is not a state Proxy
1514 */
1515 original: (state: DeclaredState) => InitialState & Partial<DeclaredState>;
1516 };
1517}
1518type InitialState<Slices extends Array<AnySliceLike | ReducerMap>> = UnionToIntersection<Slices[number] extends infer Slice ? Slice extends AnySliceLike ? WithSlice<Slice> : StateFromReducersMapObject<Slice> : never>;
1519type InitialPreloadedState<Slices extends Array<AnySliceLike | ReducerMap>> = UnionToIntersection<Slices[number] extends infer Slice ? Slice extends AnySliceLike ? WithSlicePreloadedState<Slice> : PreloadedStateShapeFromReducersMapObject<Slice> : never>;
1520declare function combineSlices<Slices extends Array<AnySliceLike | ReducerMap>>(...slices: Slices): CombinedSliceReducer<Id<InitialState<Slices>>, Id<InitialState<Slices>>, Partial<Id<InitialPreloadedState<Slices>>>>;
1521
1522declare const asyncThunkSymbol: unique symbol;
1523declare const asyncThunkCreator: {
1524 [asyncThunkSymbol]: typeof createAsyncThunk;
1525};
1526type InjectIntoConfig<NewReducerPath extends string> = InjectConfig & {
1527 reducerPath?: NewReducerPath;
1528};
1529/**
1530 * The return value of `createSlice`
1531 *
1532 * @public
1533 */
1534interface Slice<State = any, CaseReducers extends SliceCaseReducers<State> = SliceCaseReducers<State>, Name extends string = string, ReducerPath extends string = Name, Selectors extends SliceSelectors<State> = SliceSelectors<State>> {
1535 /**
1536 * The slice name.
1537 */
1538 name: Name;
1539 /**
1540 * The slice reducer path.
1541 */
1542 reducerPath: ReducerPath;
1543 /**
1544 * The slice's reducer.
1545 */
1546 reducer: Reducer<State>;
1547 /**
1548 * Action creators for the types of actions that are handled by the slice
1549 * reducer.
1550 */
1551 actions: CaseReducerActions<CaseReducers, Name>;
1552 /**
1553 * The individual case reducer functions that were passed in the `reducers` parameter.
1554 * This enables reuse and testing if they were defined inline when calling `createSlice`.
1555 */
1556 caseReducers: SliceDefinedCaseReducers<CaseReducers>;
1557 /**
1558 * Provides access to the initial state value given to the slice.
1559 * If a lazy state initializer was provided, it will be called and a fresh value returned.
1560 */
1561 getInitialState: () => State;
1562 /**
1563 * Get localised slice selectors (expects to be called with *just* the slice's state as the first parameter)
1564 */
1565 getSelectors(): Id<SliceDefinedSelectors<State, Selectors, State>>;
1566 /**
1567 * Get globalised slice selectors (`selectState` callback is expected to receive first parameter and return slice state)
1568 */
1569 getSelectors<RootState>(selectState: (rootState: RootState) => State): Id<SliceDefinedSelectors<State, Selectors, RootState>>;
1570 /**
1571 * Selectors that assume the slice's state is `rootState[slice.reducerPath]` (which is usually the case)
1572 *
1573 * Equivalent to `slice.getSelectors((state: RootState) => state[slice.reducerPath])`.
1574 */
1575 get selectors(): Id<SliceDefinedSelectors<State, Selectors, {
1576 [K in ReducerPath]: State;
1577 }>>;
1578 /**
1579 * Inject slice into provided reducer (return value from `combineSlices`), and return injected slice.
1580 */
1581 injectInto<NewReducerPath extends string = ReducerPath>(this: this, injectable: {
1582 inject: (slice: {
1583 reducerPath: string;
1584 reducer: Reducer;
1585 }, config?: InjectConfig) => void;
1586 }, config?: InjectIntoConfig<NewReducerPath>): InjectedSlice<State, CaseReducers, Name, NewReducerPath, Selectors>;
1587 /**
1588 * Select the slice state, using the slice's current reducerPath.
1589 *
1590 * Will throw an error if slice is not found.
1591 */
1592 selectSlice(state: {
1593 [K in ReducerPath]: State;
1594 }): State;
1595}
1596/**
1597 * A slice after being called with `injectInto(reducer)`.
1598 *
1599 * Selectors can now be called with an `undefined` value, in which case they use the slice's initial state.
1600 */
1601type 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'> & {
1602 /**
1603 * Get localised slice selectors (expects to be called with *just* the slice's state as the first parameter)
1604 */
1605 getSelectors(): Id<SliceDefinedSelectors<State, Selectors, State | undefined>>;
1606 /**
1607 * Get globalised slice selectors (`selectState` callback is expected to receive first parameter and return slice state)
1608 */
1609 getSelectors<RootState>(selectState: (rootState: RootState) => State | undefined): Id<SliceDefinedSelectors<State, Selectors, RootState>>;
1610 /**
1611 * Selectors that assume the slice's state is `rootState[slice.name]` (which is usually the case)
1612 *
1613 * Equivalent to `slice.getSelectors((state: RootState) => state[slice.name])`.
1614 */
1615 get selectors(): Id<SliceDefinedSelectors<State, Selectors, {
1616 [K in ReducerPath]?: State | undefined;
1617 }>>;
1618 /**
1619 * Select the slice state, using the slice's current reducerPath.
1620 *
1621 * Returns initial state if slice is not found.
1622 */
1623 selectSlice(state: {
1624 [K in ReducerPath]?: State | undefined;
1625 }): State;
1626};
1627/**
1628 * Options for `createSlice()`.
1629 *
1630 * @public
1631 */
1632interface CreateSliceOptions<State = any, CR extends SliceCaseReducers<State> = SliceCaseReducers<State>, Name extends string = string, ReducerPath extends string = Name, Selectors extends SliceSelectors<State> = SliceSelectors<State>> {
1633 /**
1634 * The slice's name. Used to namespace the generated action types.
1635 */
1636 name: Name;
1637 /**
1638 * The slice's reducer path. Used when injecting into a combined slice reducer.
1639 */
1640 reducerPath?: ReducerPath;
1641 /**
1642 * 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`.
1643 */
1644 initialState: State | (() => State);
1645 /**
1646 * A mapping from action types to action-type-specific *case reducer*
1647 * functions. For every action type, a matching action creator will be
1648 * generated using `createAction()`.
1649 */
1650 reducers: ValidateSliceCaseReducers<State, CR> | ((creators: ReducerCreators<State>) => CR);
1651 /**
1652 * A callback that receives a *builder* object to define
1653 * case reducers via calls to `builder.addCase(actionCreatorOrType, reducer)`.
1654 *
1655 *
1656 * @example
1657 ```ts
1658 import { createAction, createSlice, Action } from '@reduxjs/toolkit'
1659 const incrementBy = createAction<number>('incrementBy')
1660 const decrement = createAction('decrement')
1661
1662 interface RejectedAction extends Action {
1663 error: Error
1664 }
1665
1666 function isRejectedAction(action: Action): action is RejectedAction {
1667 return action.type.endsWith('rejected')
1668 }
1669
1670 createSlice({
1671 name: 'counter',
1672 initialState: 0,
1673 reducers: {},
1674 extraReducers: builder => {
1675 builder
1676 .addCase(incrementBy, (state, action) => {
1677 // action is inferred correctly here if using TS
1678 })
1679 // You can chain calls, or have separate `builder.addCase()` lines each time
1680 .addCase(decrement, (state, action) => {})
1681 // You can match a range of action types
1682 .addMatcher(
1683 isRejectedAction,
1684 // `action` will be inferred as a RejectedAction due to isRejectedAction being defined as a type guard
1685 (state, action) => {}
1686 )
1687 // and provide a default case if no other handlers matched
1688 .addDefaultCase((state, action) => {})
1689 }
1690 })
1691 ```
1692 */
1693 extraReducers?: (builder: ActionReducerMapBuilder<State>) => void;
1694 /**
1695 * A map of selectors that receive the slice's state and any additional arguments, and return a result.
1696 */
1697 selectors?: Selectors;
1698}
1699declare enum ReducerType {
1700 reducer = "reducer",
1701 reducerWithPrepare = "reducerWithPrepare",
1702 asyncThunk = "asyncThunk"
1703}
1704type ReducerDefinition<T extends ReducerType = ReducerType> = {
1705 _reducerDefinitionType: T;
1706};
1707type CaseReducerDefinition<S = any, A extends Action = UnknownAction> = CaseReducer<S, A> & ReducerDefinition<ReducerType.reducer>;
1708/**
1709 * A CaseReducer with a `prepare` method.
1710 *
1711 * @public
1712 */
1713type CaseReducerWithPrepare<State, Action extends PayloadAction> = {
1714 reducer: CaseReducer<State, Action>;
1715 prepare: PrepareAction<Action['payload']>;
1716};
1717type AsyncThunkSliceReducerConfig<State, ThunkArg extends any, Returned = unknown, ThunkApiConfig extends AsyncThunkConfig = {}> = AsyncThunkReducers<State, ThunkArg, Returned, ThunkApiConfig> & {
1718 options?: AsyncThunkOptions<ThunkArg, ThunkApiConfig>;
1719};
1720type AsyncThunkSliceReducerDefinition<State, ThunkArg extends any, Returned = unknown, ThunkApiConfig extends AsyncThunkConfig = {}> = AsyncThunkSliceReducerConfig<State, ThunkArg, Returned, ThunkApiConfig> & ReducerDefinition<ReducerType.asyncThunk> & {
1721 payloadCreator: AsyncThunkPayloadCreator<Returned, ThunkArg, ThunkApiConfig>;
1722};
1723/**
1724 * Providing these as part of the config would cause circular types, so we disallow passing them
1725 */
1726type PreventCircular<ThunkApiConfig> = {
1727 [K in keyof ThunkApiConfig]: K extends 'state' | 'dispatch' ? never : ThunkApiConfig[K];
1728};
1729interface AsyncThunkCreator<State, CurriedThunkApiConfig extends PreventCircular<AsyncThunkConfig> = PreventCircular<AsyncThunkConfig>> {
1730 <Returned, ThunkArg = void>(payloadCreator: AsyncThunkPayloadCreator<Returned, ThunkArg, CurriedThunkApiConfig>, config?: AsyncThunkSliceReducerConfig<State, ThunkArg, Returned, CurriedThunkApiConfig>): AsyncThunkSliceReducerDefinition<State, ThunkArg, Returned, CurriedThunkApiConfig>;
1731 <Returned, ThunkArg, ThunkApiConfig extends PreventCircular<AsyncThunkConfig> = {}>(payloadCreator: AsyncThunkPayloadCreator<Returned, ThunkArg, ThunkApiConfig>, config?: AsyncThunkSliceReducerConfig<State, ThunkArg, Returned, ThunkApiConfig>): AsyncThunkSliceReducerDefinition<State, ThunkArg, Returned, ThunkApiConfig>;
1732 withTypes<ThunkApiConfig extends PreventCircular<AsyncThunkConfig>>(): AsyncThunkCreator<State, OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>>;
1733}
1734interface ReducerCreators<State> {
1735 reducer(caseReducer: CaseReducer<State, PayloadAction>): CaseReducerDefinition<State, PayloadAction>;
1736 reducer<Payload>(caseReducer: CaseReducer<State, PayloadAction<Payload>>): CaseReducerDefinition<State, PayloadAction<Payload>>;
1737 asyncThunk: AsyncThunkCreator<State>;
1738 preparedReducer<Prepare extends PrepareAction<any>>(prepare: Prepare, reducer: CaseReducer<State, ReturnType<_ActionCreatorWithPreparedPayload<Prepare>>>): {
1739 _reducerDefinitionType: ReducerType.reducerWithPrepare;
1740 prepare: Prepare;
1741 reducer: CaseReducer<State, ReturnType<_ActionCreatorWithPreparedPayload<Prepare>>>;
1742 };
1743}
1744/**
1745 * The type describing a slice's `reducers` option.
1746 *
1747 * @public
1748 */
1749type SliceCaseReducers<State> = Record<string, ReducerDefinition> | Record<string, CaseReducer<State, PayloadAction<any>> | CaseReducerWithPrepare<State, PayloadAction<any, string, any, any>>>;
1750/**
1751 * The type describing a slice's `selectors` option.
1752 */
1753type SliceSelectors<State> = {
1754 [K: string]: (sliceState: State, ...args: any[]) => any;
1755};
1756type SliceActionType<SliceName extends string, ActionName extends keyof any> = ActionName extends string | number ? `${SliceName}/${ActionName}` : string;
1757/**
1758 * Derives the slice's `actions` property from the `reducers` options
1759 *
1760 * @public
1761 */
1762type CaseReducerActions<CaseReducers extends SliceCaseReducers<any>, SliceName extends string> = {
1763 [Type in keyof CaseReducers]: CaseReducers[Type] extends infer Definition ? Definition extends {
1764 prepare: any;
1765 } ? ActionCreatorForCaseReducerWithPrepare<Definition, SliceActionType<SliceName, Type>> : Definition extends AsyncThunkSliceReducerDefinition<any, infer ThunkArg, infer Returned, infer ThunkApiConfig> ? AsyncThunk<Returned, ThunkArg, ThunkApiConfig> : Definition extends {
1766 reducer: any;
1767 } ? ActionCreatorForCaseReducer<Definition['reducer'], SliceActionType<SliceName, Type>> : ActionCreatorForCaseReducer<Definition, SliceActionType<SliceName, Type>> : never;
1768};
1769/**
1770 * Get a `PayloadActionCreator` type for a passed `CaseReducerWithPrepare`
1771 *
1772 * @internal
1773 */
1774type ActionCreatorForCaseReducerWithPrepare<CR extends {
1775 prepare: any;
1776}, Type extends string> = _ActionCreatorWithPreparedPayload<CR['prepare'], Type>;
1777/**
1778 * Get a `PayloadActionCreator` type for a passed `CaseReducer`
1779 *
1780 * @internal
1781 */
1782type ActionCreatorForCaseReducer<CR, Type extends string> = CR extends (state: any, action: infer Action) => any ? Action extends {
1783 payload: infer P;
1784} ? PayloadActionCreator<P, Type> : ActionCreatorWithoutPayload<Type> : ActionCreatorWithoutPayload<Type>;
1785/**
1786 * Extracts the CaseReducers out of a `reducers` object, even if they are
1787 * tested into a `CaseReducerWithPrepare`.
1788 *
1789 * @internal
1790 */
1791type SliceDefinedCaseReducers<CaseReducers extends SliceCaseReducers<any>> = {
1792 [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 {
1793 reducer: infer Reducer;
1794 } ? Reducer : Definition : never;
1795};
1796type RemappedSelector<S extends Selector, NewState> = S extends Selector<any, infer R, infer P> ? Selector<NewState, R, P> & {
1797 unwrapped: S;
1798} : never;
1799/**
1800 * Extracts the final selector type from the `selectors` object.
1801 *
1802 * Removes the `string` index signature from the default value.
1803 */
1804type SliceDefinedSelectors<State, Selectors extends SliceSelectors<State>, RootState> = {
1805 [K in keyof Selectors as string extends K ? never : K]: RemappedSelector<Selectors[K], RootState>;
1806};
1807/**
1808 * Used on a SliceCaseReducers object.
1809 * Ensures that if a CaseReducer is a `CaseReducerWithPrepare`, that
1810 * the `reducer` and the `prepare` function use the same type of `payload`.
1811 *
1812 * Might do additional such checks in the future.
1813 *
1814 * This type is only ever useful if you want to write your own wrapper around
1815 * `createSlice`. Please don't use it otherwise!
1816 *
1817 * @public
1818 */
1819type ValidateSliceCaseReducers<S, ACR extends SliceCaseReducers<S>> = ACR & {
1820 [T in keyof ACR]: ACR[T] extends {
1821 reducer(s: S, action?: infer A): any;
1822 } ? {
1823 prepare(...a: never[]): Omit<A, 'type'>;
1824 } : {};
1825};
1826interface BuildCreateSliceConfig {
1827 creators?: {
1828 asyncThunk?: typeof asyncThunkCreator;
1829 };
1830}
1831declare 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>;
1832/**
1833 * A function that accepts an initial state, an object full of reducer
1834 * functions, and a "slice name", and automatically generates
1835 * action creators and action types that correspond to the
1836 * reducers and state.
1837 *
1838 * @public
1839 */
1840declare 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>;
1841
1842type AnyCreateSelectorFunction = CreateSelectorFunction<any, any, any>;
1843type GetSelectorsOptions = {
1844 createSelector?: AnyCreateSelectorFunction;
1845};
1846
1847/**
1848 * @public
1849 */
1850type EntityId = number | string;
1851/**
1852 * @public
1853 */
1854type Comparer<T> = (a: T, b: T) => number;
1855/**
1856 * @public
1857 */
1858type IdSelector<T, Id extends EntityId> = (model: T) => Id;
1859/**
1860 * @public
1861 */
1862type Update<T, Id extends EntityId> = {
1863 id: Id;
1864 changes: Partial<T>;
1865};
1866/**
1867 * @public
1868 */
1869interface EntityState<T, Id extends EntityId> {
1870 ids: Id[];
1871 entities: Record<Id, T>;
1872}
1873/**
1874 * @public
1875 */
1876interface EntityAdapterOptions<T, Id extends EntityId> {
1877 selectId?: IdSelector<T, Id>;
1878 sortComparer?: false | Comparer<T>;
1879}
1880type PreventAny<S, T, Id extends EntityId> = CastAny<S, EntityState<T, Id>>;
1881type DraftableEntityState<T, Id extends EntityId> = EntityState<T, Id> | Draft<EntityState<T, Id>>;
1882/**
1883 * @public
1884 */
1885interface EntityStateAdapter<T, Id extends EntityId> {
1886 addOne<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, entity: T): S;
1887 addOne<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, action: PayloadAction<T>): S;
1888 addMany<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, entities: readonly T[] | Record<Id, T>): S;
1889 addMany<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, entities: PayloadAction<readonly T[] | Record<Id, T>>): S;
1890 setOne<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, entity: T): S;
1891 setOne<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, action: PayloadAction<T>): S;
1892 setMany<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, entities: readonly T[] | Record<Id, T>): S;
1893 setMany<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, entities: PayloadAction<readonly T[] | Record<Id, T>>): S;
1894 setAll<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, entities: readonly T[] | Record<Id, T>): S;
1895 setAll<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, entities: PayloadAction<readonly T[] | Record<Id, T>>): S;
1896 removeOne<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, key: Id): S;
1897 removeOne<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, key: PayloadAction<Id>): S;
1898 removeMany<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, keys: readonly Id[]): S;
1899 removeMany<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, keys: PayloadAction<readonly Id[]>): S;
1900 removeAll<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>): S;
1901 updateOne<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, update: Update<T, Id>): S;
1902 updateOne<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, update: PayloadAction<Update<T, Id>>): S;
1903 updateMany<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, updates: ReadonlyArray<Update<T, Id>>): S;
1904 updateMany<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, updates: PayloadAction<ReadonlyArray<Update<T, Id>>>): S;
1905 upsertOne<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, entity: T): S;
1906 upsertOne<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, entity: PayloadAction<T>): S;
1907 upsertMany<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, entities: readonly T[] | Record<Id, T>): S;
1908 upsertMany<S extends DraftableEntityState<T, Id>>(state: PreventAny<S, T, Id>, entities: PayloadAction<readonly T[] | Record<Id, T>>): S;
1909}
1910/**
1911 * @public
1912 */
1913interface EntitySelectors<T, V, IdType extends EntityId> {
1914 selectIds: (state: V) => IdType[];
1915 selectEntities: (state: V) => Record<IdType, T>;
1916 selectAll: (state: V) => T[];
1917 selectTotal: (state: V) => number;
1918 selectById: (state: V, id: IdType) => Id<UncheckedIndexedAccess<T>>;
1919}
1920/**
1921 * @public
1922 */
1923interface EntityStateFactory<T, Id extends EntityId> {
1924 getInitialState(state?: undefined, entities?: Record<Id, T> | readonly T[]): EntityState<T, Id>;
1925 getInitialState<S extends object>(state: S, entities?: Record<Id, T> | readonly T[]): EntityState<T, Id> & S;
1926}
1927/**
1928 * @public
1929 */
1930interface EntityAdapter<T, Id extends EntityId> extends EntityStateAdapter<T, Id>, EntityStateFactory<T, Id>, Required<EntityAdapterOptions<T, Id>> {
1931 getSelectors(selectState?: undefined, options?: GetSelectorsOptions): EntitySelectors<T, EntityState<T, Id>, Id>;
1932 getSelectors<V>(selectState: (state: V) => EntityState<T, Id>, options?: GetSelectorsOptions): EntitySelectors<T, V, Id>;
1933}
1934
1935declare function createEntityAdapter<T, Id extends EntityId>(options: WithRequiredProp<EntityAdapterOptions<T, Id>, 'selectId'>): EntityAdapter<T, Id>;
1936declare function createEntityAdapter<T extends {
1937 id: EntityId;
1938}>(options?: Omit<EntityAdapterOptions<T, T['id']>, 'selectId'>): EntityAdapter<T, T['id']>;
1939
1940/** @public */
1941type ActionMatchingAnyOf<Matchers extends Matcher<any>[]> = ActionFromMatcher<Matchers[number]>;
1942/** @public */
1943type ActionMatchingAllOf<Matchers extends Matcher<any>[]> = UnionToIntersection<ActionMatchingAnyOf<Matchers>>;
1944/**
1945 * A higher-order function that returns a function that may be used to check
1946 * whether an action matches any one of the supplied type guards or action
1947 * creators.
1948 *
1949 * @param matchers The type guards or action creators to match against.
1950 *
1951 * @public
1952 */
1953declare function isAnyOf<Matchers extends Matcher<any>[]>(...matchers: Matchers): (action: any) => action is ActionMatchingAnyOf<Matchers>;
1954/**
1955 * A higher-order function that returns a function that may be used to check
1956 * whether an action matches all of the supplied type guards or action
1957 * creators.
1958 *
1959 * @param matchers The type guards or action creators to match against.
1960 *
1961 * @public
1962 */
1963declare function isAllOf<Matchers extends Matcher<any>[]>(...matchers: Matchers): (action: any) => action is ActionMatchingAllOf<Matchers>;
1964type UnknownAsyncThunkPendingAction = ReturnType<AsyncThunkPendingActionCreator<unknown>>;
1965type PendingActionFromAsyncThunk<T extends AnyAsyncThunk> = ActionFromMatcher<T['pending']>;
1966/**
1967 * A higher-order function that returns a function that may be used to check
1968 * whether an action was created by an async thunk action creator, and that
1969 * the action is pending.
1970 *
1971 * @public
1972 */
1973declare function isPending(): (action: any) => action is UnknownAsyncThunkPendingAction;
1974/**
1975 * A higher-order function that returns a function that may be used to check
1976 * whether an action belongs to one of the provided async thunk action creators,
1977 * and that the action is pending.
1978 *
1979 * @param asyncThunks (optional) The async thunk action creators to match against.
1980 *
1981 * @public
1982 */
1983declare function isPending<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks): (action: any) => action is PendingActionFromAsyncThunk<AsyncThunks[number]>;
1984/**
1985 * Tests if `action` is a pending thunk action
1986 * @public
1987 */
1988declare function isPending(action: any): action is UnknownAsyncThunkPendingAction;
1989type UnknownAsyncThunkRejectedAction = ReturnType<AsyncThunkRejectedActionCreator<unknown, unknown>>;
1990type RejectedActionFromAsyncThunk<T extends AnyAsyncThunk> = ActionFromMatcher<T['rejected']>;
1991/**
1992 * A higher-order function that returns a function that may be used to check
1993 * whether an action was created by an async thunk action creator, and that
1994 * the action is rejected.
1995 *
1996 * @public
1997 */
1998declare function isRejected(): (action: any) => action is UnknownAsyncThunkRejectedAction;
1999/**
2000 * A higher-order function that returns a function that may be used to check
2001 * whether an action belongs to one of the provided async thunk action creators,
2002 * and that the action is rejected.
2003 *
2004 * @param asyncThunks (optional) The async thunk action creators to match against.
2005 *
2006 * @public
2007 */
2008declare function isRejected<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks): (action: any) => action is RejectedActionFromAsyncThunk<AsyncThunks[number]>;
2009/**
2010 * Tests if `action` is a rejected thunk action
2011 * @public
2012 */
2013declare function isRejected(action: any): action is UnknownAsyncThunkRejectedAction;
2014type RejectedWithValueActionFromAsyncThunk<T extends AnyAsyncThunk> = ActionFromMatcher<T['rejected']> & (T extends AsyncThunk<any, any, {
2015 rejectValue: infer RejectedValue;
2016}> ? {
2017 payload: RejectedValue;
2018} : unknown);
2019/**
2020 * A higher-order function that returns a function that may be used to check
2021 * whether an action was created by an async thunk action creator, and that
2022 * the action is rejected with value.
2023 *
2024 * @public
2025 */
2026declare function isRejectedWithValue(): (action: any) => action is UnknownAsyncThunkRejectedAction;
2027/**
2028 * A higher-order function that returns a function that may be used to check
2029 * whether an action belongs to one of the provided async thunk action creators,
2030 * and that the action is rejected with value.
2031 *
2032 * @param asyncThunks (optional) The async thunk action creators to match against.
2033 *
2034 * @public
2035 */
2036declare function isRejectedWithValue<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks): (action: any) => action is RejectedWithValueActionFromAsyncThunk<AsyncThunks[number]>;
2037/**
2038 * Tests if `action` is a rejected thunk action with value
2039 * @public
2040 */
2041declare function isRejectedWithValue(action: any): action is UnknownAsyncThunkRejectedAction;
2042type UnknownAsyncThunkFulfilledAction = ReturnType<AsyncThunkFulfilledActionCreator<unknown, unknown>>;
2043type FulfilledActionFromAsyncThunk<T extends AnyAsyncThunk> = ActionFromMatcher<T['fulfilled']>;
2044/**
2045 * A higher-order function that returns a function that may be used to check
2046 * whether an action was created by an async thunk action creator, and that
2047 * the action is fulfilled.
2048 *
2049 * @public
2050 */
2051declare function isFulfilled(): (action: any) => action is UnknownAsyncThunkFulfilledAction;
2052/**
2053 * A higher-order function that returns a function that may be used to check
2054 * whether an action belongs to one of the provided async thunk action creators,
2055 * and that the action is fulfilled.
2056 *
2057 * @param asyncThunks (optional) The async thunk action creators to match against.
2058 *
2059 * @public
2060 */
2061declare function isFulfilled<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks): (action: any) => action is FulfilledActionFromAsyncThunk<AsyncThunks[number]>;
2062/**
2063 * Tests if `action` is a fulfilled thunk action
2064 * @public
2065 */
2066declare function isFulfilled(action: any): action is UnknownAsyncThunkFulfilledAction;
2067type UnknownAsyncThunkAction = UnknownAsyncThunkPendingAction | UnknownAsyncThunkRejectedAction | UnknownAsyncThunkFulfilledAction;
2068type AnyAsyncThunk = {
2069 pending: {
2070 match: (action: any) => action is any;
2071 };
2072 fulfilled: {
2073 match: (action: any) => action is any;
2074 };
2075 rejected: {
2076 match: (action: any) => action is any;
2077 };
2078};
2079type ActionsFromAsyncThunk<T extends AnyAsyncThunk> = ActionFromMatcher<T['pending']> | ActionFromMatcher<T['fulfilled']> | ActionFromMatcher<T['rejected']>;
2080/**
2081 * A higher-order function that returns a function that may be used to check
2082 * whether an action was created by an async thunk action creator.
2083 *
2084 * @public
2085 */
2086declare function isAsyncThunkAction(): (action: any) => action is UnknownAsyncThunkAction;
2087/**
2088 * A higher-order function that returns a function that may be used to check
2089 * whether an action belongs to one of the provided async thunk action creators.
2090 *
2091 * @param asyncThunks (optional) The async thunk action creators to match against.
2092 *
2093 * @public
2094 */
2095declare function isAsyncThunkAction<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks): (action: any) => action is ActionsFromAsyncThunk<AsyncThunks[number]>;
2096/**
2097 * Tests if `action` is a thunk action
2098 * @public
2099 */
2100declare function isAsyncThunkAction(action: any): action is UnknownAsyncThunkAction;
2101
2102/**
2103 *
2104 * @public
2105 */
2106declare let nanoid: (size?: number) => string;
2107
2108declare class TaskAbortError implements SerializedError {
2109 code: string | undefined;
2110 name: string;
2111 message: string;
2112 constructor(code: string | undefined);
2113}
2114
2115/**
2116 * Types copied from RTK
2117 */
2118/** @internal */
2119type TypedActionCreatorWithMatchFunction<Type extends string> = TypedActionCreator<Type> & {
2120 match: MatchFunction<any>;
2121};
2122/** @internal */
2123type AnyListenerPredicate<State> = (action: UnknownAction, currentState: State, originalState: State) => boolean;
2124/** @public */
2125type ListenerPredicate<ActionType extends Action, State> = (action: UnknownAction, currentState: State, originalState: State) => action is ActionType;
2126/** @public */
2127interface ConditionFunction<State> {
2128 (predicate: AnyListenerPredicate<State>, timeout?: number): Promise<boolean>;
2129 (predicate: AnyListenerPredicate<State>, timeout?: number): Promise<boolean>;
2130 (predicate: () => boolean, timeout?: number): Promise<boolean>;
2131}
2132/** @internal */
2133type MatchFunction<T> = (v: any) => v is T;
2134/** @public */
2135interface ForkedTaskAPI {
2136 /**
2137 * Returns a promise that resolves when `waitFor` resolves or
2138 * rejects if the task or the parent listener has been cancelled or is completed.
2139 */
2140 pause<W>(waitFor: Promise<W>): Promise<W>;
2141 /**
2142 * Returns a promise that resolves after `timeoutMs` or
2143 * rejects if the task or the parent listener has been cancelled or is completed.
2144 * @param timeoutMs
2145 */
2146 delay(timeoutMs: number): Promise<void>;
2147 /**
2148 * An abort signal whose `aborted` property is set to `true`
2149 * if the task execution is either aborted or completed.
2150 * @see https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal
2151 */
2152 signal: AbortSignal;
2153}
2154/** @public */
2155interface AsyncTaskExecutor<T> {
2156 (forkApi: ForkedTaskAPI): Promise<T>;
2157}
2158/** @public */
2159interface SyncTaskExecutor<T> {
2160 (forkApi: ForkedTaskAPI): T;
2161}
2162/** @public */
2163type ForkedTaskExecutor<T> = AsyncTaskExecutor<T> | SyncTaskExecutor<T>;
2164/** @public */
2165type TaskResolved<T> = {
2166 readonly status: 'ok';
2167 readonly value: T;
2168};
2169/** @public */
2170type TaskRejected = {
2171 readonly status: 'rejected';
2172 readonly error: unknown;
2173};
2174/** @public */
2175type TaskCancelled = {
2176 readonly status: 'cancelled';
2177 readonly error: TaskAbortError;
2178};
2179/** @public */
2180type TaskResult<Value> = TaskResolved<Value> | TaskRejected | TaskCancelled;
2181/** @public */
2182interface ForkedTask<T> {
2183 /**
2184 * A promise that resolves when the task is either completed or cancelled or rejects
2185 * if parent listener execution is cancelled or completed.
2186 *
2187 * ### Example
2188 * ```ts
2189 * const result = await fork(async (forkApi) => Promise.resolve(4)).result
2190 *
2191 * if(result.status === 'ok') {
2192 * console.log(result.value) // logs 4
2193 * }}
2194 * ```
2195 */
2196 result: Promise<TaskResult<T>>;
2197 /**
2198 * Cancel task if it is in progress or not yet started,
2199 * it is noop otherwise.
2200 */
2201 cancel(): void;
2202}
2203/** @public */
2204interface ForkOptions {
2205 /**
2206 * If true, causes the parent task to not be marked as complete until
2207 * all autoJoined forks have completed or failed.
2208 */
2209 autoJoin: boolean;
2210}
2211/** @public */
2212interface ListenerEffectAPI<State, DispatchType extends Dispatch, ExtraArgument = unknown> extends MiddlewareAPI<DispatchType, State> {
2213 /**
2214 * Returns the store state as it existed when the action was originally dispatched, _before_ the reducers ran.
2215 *
2216 * ### Synchronous invocation
2217 *
2218 * This function can **only** be invoked **synchronously**, it throws error otherwise.
2219 *
2220 * @example
2221 *
2222 * ```ts
2223 * middleware.startListening({
2224 * predicate: () => true,
2225 * async effect(_, { getOriginalState }) {
2226 * getOriginalState(); // sync: OK!
2227 *
2228 * setTimeout(getOriginalState, 0); // async: throws Error
2229 *
2230 * await Promise().resolve();
2231 *
2232 * getOriginalState() // async: throws Error
2233 * }
2234 * })
2235 * ```
2236 */
2237 getOriginalState: () => State;
2238 /**
2239 * Removes the listener entry from the middleware and prevent future instances of the listener from running.
2240 *
2241 * It does **not** cancel any active instances.
2242 */
2243 unsubscribe(): void;
2244 /**
2245 * It will subscribe a listener if it was previously removed, noop otherwise.
2246 */
2247 subscribe(): void;
2248 /**
2249 * Returns a promise that resolves when the input predicate returns `true` or
2250 * rejects if the listener has been cancelled or is completed.
2251 *
2252 * The return value is `true` if the predicate succeeds or `false` if a timeout is provided and expires first.
2253 *
2254 * ### Example
2255 *
2256 * ```ts
2257 * const updateBy = createAction<number>('counter/updateBy');
2258 *
2259 * middleware.startListening({
2260 * actionCreator: updateBy,
2261 * async effect(_, { condition }) {
2262 * // wait at most 3s for `updateBy` actions.
2263 * if(await condition(updateBy.match, 3_000)) {
2264 * // `updateBy` has been dispatched twice in less than 3s.
2265 * }
2266 * }
2267 * })
2268 * ```
2269 */
2270 condition: ConditionFunction<State>;
2271 /**
2272 * Returns a promise that resolves when the input predicate returns `true` or
2273 * rejects if the listener has been cancelled or is completed.
2274 *
2275 * The return value is the `[action, currentState, previousState]` combination that the predicate saw as arguments.
2276 *
2277 * The promise resolves to null if a timeout is provided and expires first,
2278 *
2279 * ### Example
2280 *
2281 * ```ts
2282 * const updateBy = createAction<number>('counter/updateBy');
2283 *
2284 * middleware.startListening({
2285 * actionCreator: updateBy,
2286 * async effect(_, { take }) {
2287 * const [{ payload }] = await take(updateBy.match);
2288 * console.log(payload); // logs 5;
2289 * }
2290 * })
2291 *
2292 * store.dispatch(updateBy(5));
2293 * ```
2294 */
2295 take: TakePattern<State>;
2296 /**
2297 * Cancels all other running instances of this same listener except for the one that made this call.
2298 */
2299 cancelActiveListeners: () => void;
2300 /**
2301 * Cancels the instance of this listener that made this call.
2302 */
2303 cancel: () => void;
2304 /**
2305 * Throws a `TaskAbortError` if this listener has been cancelled
2306 */
2307 throwIfCancelled: () => void;
2308 /**
2309 * An abort signal whose `aborted` property is set to `true`
2310 * if the listener execution is either aborted or completed.
2311 * @see https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal
2312 */
2313 signal: AbortSignal;
2314 /**
2315 * Returns a promise that resolves after `timeoutMs` or
2316 * rejects if the listener has been cancelled or is completed.
2317 */
2318 delay(timeoutMs: number): Promise<void>;
2319 /**
2320 * Queues in the next microtask the execution of a task.
2321 * @param executor
2322 * @param options
2323 */
2324 fork<T>(executor: ForkedTaskExecutor<T>, options?: ForkOptions): ForkedTask<T>;
2325 /**
2326 * Returns a promise that resolves when `waitFor` resolves or
2327 * rejects if the listener has been cancelled or is completed.
2328 * @param promise
2329 */
2330 pause<M>(promise: Promise<M>): Promise<M>;
2331 extra: ExtraArgument;
2332}
2333/** @public */
2334type ListenerEffect<ActionType extends Action, State, DispatchType extends Dispatch, ExtraArgument = unknown> = (action: ActionType, api: ListenerEffectAPI<State, DispatchType, ExtraArgument>) => void | Promise<void>;
2335/**
2336 * @public
2337 * Additional infos regarding the error raised.
2338 */
2339interface ListenerErrorInfo {
2340 /**
2341 * Which function has generated the exception.
2342 */
2343 raisedBy: 'effect' | 'predicate';
2344}
2345/**
2346 * @public
2347 * Gets notified with synchronous and asynchronous errors raised by `listeners` or `predicates`.
2348 * @param error The thrown error.
2349 * @param errorInfo Additional information regarding the thrown error.
2350 */
2351interface ListenerErrorHandler {
2352 (error: unknown, errorInfo: ListenerErrorInfo): void;
2353}
2354/** @public */
2355interface CreateListenerMiddlewareOptions<ExtraArgument = unknown> {
2356 extra?: ExtraArgument;
2357 /**
2358 * Receives synchronous errors that are raised by `listener` and `listenerOption.predicate`.
2359 */
2360 onError?: ListenerErrorHandler;
2361}
2362/** @public */
2363type ListenerMiddleware<State = unknown, DispatchType extends ThunkDispatch<State, unknown, Action> = ThunkDispatch<State, unknown, UnknownAction>, ExtraArgument = unknown> = Middleware<{
2364 (action: Action<'listenerMiddleware/add'>): UnsubscribeListener;
2365}, State, DispatchType>;
2366/** @public */
2367interface ListenerMiddlewareInstance<StateType = unknown, DispatchType extends ThunkDispatch<StateType, unknown, Action> = ThunkDispatch<StateType, unknown, UnknownAction>, ExtraArgument = unknown> {
2368 middleware: ListenerMiddleware<StateType, DispatchType, ExtraArgument>;
2369 startListening: AddListenerOverloads<UnsubscribeListener, StateType, DispatchType, ExtraArgument> & TypedStartListening<StateType, DispatchType, ExtraArgument>;
2370 stopListening: RemoveListenerOverloads<StateType, DispatchType> & TypedStopListening<StateType, DispatchType>;
2371 /**
2372 * Unsubscribes all listeners, cancels running listeners and tasks.
2373 */
2374 clearListeners: () => void;
2375}
2376/**
2377 * API Function Overloads
2378 */
2379/** @public */
2380type TakePatternOutputWithoutTimeout<State, Predicate extends AnyListenerPredicate<State>> = Predicate extends MatchFunction<infer ActionType> ? Promise<[ActionType, State, State]> : Promise<[UnknownAction, State, State]>;
2381/** @public */
2382type TakePatternOutputWithTimeout<State, Predicate extends AnyListenerPredicate<State>> = Predicate extends MatchFunction<infer ActionType> ? Promise<[ActionType, State, State] | null> : Promise<[UnknownAction, State, State] | null>;
2383/** @public */
2384interface TakePattern<State> {
2385 <Predicate extends AnyListenerPredicate<State>>(predicate: Predicate): TakePatternOutputWithoutTimeout<State, Predicate>;
2386 <Predicate extends AnyListenerPredicate<State>>(predicate: Predicate, timeout: number): TakePatternOutputWithTimeout<State, Predicate>;
2387 <Predicate extends AnyListenerPredicate<State>>(predicate: Predicate, timeout?: number | undefined): TakePatternOutputWithTimeout<State, Predicate>;
2388}
2389/** @public */
2390interface UnsubscribeListenerOptions {
2391 cancelActive?: true;
2392}
2393/** @public */
2394type UnsubscribeListener = (unsubscribeOptions?: UnsubscribeListenerOptions) => void;
2395/**
2396 * @public
2397 * 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
2398 */
2399type AddListenerOverloads<Return, StateType = unknown, DispatchType extends Dispatch = ThunkDispatch<StateType, unknown, UnknownAction>, ExtraArgument = unknown, AdditionalOptions = unknown> = {
2400 /** Accepts a "listener predicate" that is also a TS type predicate for the action*/
2401 <MiddlewareActionType extends UnknownAction, ListenerPredicateType extends ListenerPredicate<MiddlewareActionType, StateType>>(options: {
2402 actionCreator?: never;
2403 type?: never;
2404 matcher?: never;
2405 predicate: ListenerPredicateType;
2406 effect: ListenerEffect<ListenerPredicateGuardedActionType<ListenerPredicateType>, StateType, DispatchType, ExtraArgument>;
2407 } & AdditionalOptions): Return;
2408 /** Accepts an RTK action creator, like `incrementByAmount` */
2409 <ActionCreatorType extends TypedActionCreatorWithMatchFunction<any>>(options: {
2410 actionCreator: ActionCreatorType;
2411 type?: never;
2412 matcher?: never;
2413 predicate?: never;
2414 effect: ListenerEffect<ReturnType<ActionCreatorType>, StateType, DispatchType, ExtraArgument>;
2415 } & AdditionalOptions): Return;
2416 /** Accepts a specific action type string */
2417 <T extends string>(options: {
2418 actionCreator?: never;
2419 type: T;
2420 matcher?: never;
2421 predicate?: never;
2422 effect: ListenerEffect<Action<T>, StateType, DispatchType, ExtraArgument>;
2423 } & AdditionalOptions): Return;
2424 /** Accepts an RTK matcher function, such as `incrementByAmount.match` */
2425 <MatchFunctionType extends MatchFunction<UnknownAction>>(options: {
2426 actionCreator?: never;
2427 type?: never;
2428 matcher: MatchFunctionType;
2429 predicate?: never;
2430 effect: ListenerEffect<GuardedType<MatchFunctionType>, StateType, DispatchType, ExtraArgument>;
2431 } & AdditionalOptions): Return;
2432 /** Accepts a "listener predicate" that just returns a boolean, no type assertion */
2433 <ListenerPredicateType extends AnyListenerPredicate<StateType>>(options: {
2434 actionCreator?: never;
2435 type?: never;
2436 matcher?: never;
2437 predicate: ListenerPredicateType;
2438 effect: ListenerEffect<UnknownAction, StateType, DispatchType, ExtraArgument>;
2439 } & AdditionalOptions): Return;
2440};
2441/** @public */
2442type RemoveListenerOverloads<StateType = unknown, DispatchType extends Dispatch = ThunkDispatch<StateType, unknown, UnknownAction>, ExtraArgument = unknown> = AddListenerOverloads<boolean, StateType, DispatchType, ExtraArgument, UnsubscribeListenerOptions>;
2443/**
2444 * A "pre-typed" version of `addListenerAction`, so the listener args are well-typed
2445 *
2446 * @public
2447 */
2448type 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> & {
2449 /**
2450 * Creates a "pre-typed" version of `addListener`
2451 * where the `state`, `dispatch` and `extra` types are predefined.
2452 *
2453 * This allows you to set the `state`, `dispatch` and `extra` types once,
2454 * eliminating the need to specify them with every `addListener` call.
2455 *
2456 * @returns A pre-typed `addListener` with the state, dispatch and extra types already defined.
2457 *
2458 * @example
2459 * ```ts
2460 * import { addListener } from '@reduxjs/toolkit'
2461 *
2462 * export const addAppListener = addListener.withTypes<RootState, AppDispatch, ExtraArguments>()
2463 * ```
2464 *
2465 * @template OverrideStateType - The specific type of state the middleware listener operates on.
2466 * @template OverrideDispatchType - The specific type of the dispatch function.
2467 * @template OverrideExtraArgument - The specific type of the extra object.
2468 *
2469 * @since 2.1.0
2470 */
2471 withTypes: <OverrideStateType extends StateType, OverrideDispatchType extends Dispatch = ThunkDispatch<OverrideStateType, unknown, UnknownAction>, OverrideExtraArgument = unknown>() => TypedAddListener<OverrideStateType, OverrideDispatchType, OverrideExtraArgument>;
2472};
2473/**
2474 * A "pre-typed" version of `removeListenerAction`, so the listener args are well-typed
2475 *
2476 * @public
2477 */
2478type 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> & {
2479 /**
2480 * Creates a "pre-typed" version of `removeListener`
2481 * where the `state`, `dispatch` and `extra` types are predefined.
2482 *
2483 * This allows you to set the `state`, `dispatch` and `extra` types once,
2484 * eliminating the need to specify them with every `removeListener` call.
2485 *
2486 * @returns A pre-typed `removeListener` with the state, dispatch and extra
2487 * types already defined.
2488 *
2489 * @example
2490 * ```ts
2491 * import { removeListener } from '@reduxjs/toolkit'
2492 *
2493 * export const removeAppListener = removeListener.withTypes<
2494 * RootState,
2495 * AppDispatch,
2496 * ExtraArguments
2497 * >()
2498 * ```
2499 *
2500 * @template OverrideStateType - The specific type of state the middleware listener operates on.
2501 * @template OverrideDispatchType - The specific type of the dispatch function.
2502 * @template OverrideExtraArgument - The specific type of the extra object.
2503 *
2504 * @since 2.1.0
2505 */
2506 withTypes: <OverrideStateType extends StateType, OverrideDispatchType extends Dispatch = ThunkDispatch<OverrideStateType, unknown, UnknownAction>, OverrideExtraArgument = unknown>() => TypedRemoveListener<OverrideStateType, OverrideDispatchType, OverrideExtraArgument>;
2507};
2508/**
2509 * A "pre-typed" version of `middleware.startListening`, so the listener args are well-typed
2510 *
2511 * @public
2512 */
2513type TypedStartListening<StateType, DispatchType extends Dispatch = ThunkDispatch<StateType, unknown, UnknownAction>, ExtraArgument = unknown> = AddListenerOverloads<UnsubscribeListener, StateType, DispatchType, ExtraArgument> & {
2514 /**
2515 * Creates a "pre-typed" version of
2516 * {@linkcode ListenerMiddlewareInstance.startListening startListening}
2517 * where the `state`, `dispatch` and `extra` types are predefined.
2518 *
2519 * This allows you to set the `state`, `dispatch` and `extra` types once,
2520 * eliminating the need to specify them with every
2521 * {@linkcode ListenerMiddlewareInstance.startListening startListening} call.
2522 *
2523 * @returns A pre-typed `startListening` with the state, dispatch and extra types already defined.
2524 *
2525 * @example
2526 * ```ts
2527 * import { createListenerMiddleware } from '@reduxjs/toolkit'
2528 *
2529 * const listenerMiddleware = createListenerMiddleware()
2530 *
2531 * export const startAppListening = listenerMiddleware.startListening.withTypes<
2532 * RootState,
2533 * AppDispatch,
2534 * ExtraArguments
2535 * >()
2536 * ```
2537 *
2538 * @template OverrideStateType - The specific type of state the middleware listener operates on.
2539 * @template OverrideDispatchType - The specific type of the dispatch function.
2540 * @template OverrideExtraArgument - The specific type of the extra object.
2541 *
2542 * @since 2.1.0
2543 */
2544 withTypes: <OverrideStateType extends StateType, OverrideDispatchType extends Dispatch = ThunkDispatch<OverrideStateType, unknown, UnknownAction>, OverrideExtraArgument = unknown>() => TypedStartListening<OverrideStateType, OverrideDispatchType, OverrideExtraArgument>;
2545};
2546/**
2547 * A "pre-typed" version of `middleware.stopListening`, so the listener args are well-typed
2548 *
2549 * @public
2550 */
2551type TypedStopListening<StateType, DispatchType extends Dispatch = ThunkDispatch<StateType, unknown, UnknownAction>, ExtraArgument = unknown> = RemoveListenerOverloads<StateType, DispatchType, ExtraArgument> & {
2552 /**
2553 * Creates a "pre-typed" version of
2554 * {@linkcode ListenerMiddlewareInstance.stopListening stopListening}
2555 * where the `state`, `dispatch` and `extra` types are predefined.
2556 *
2557 * This allows you to set the `state`, `dispatch` and `extra` types once,
2558 * eliminating the need to specify them with every
2559 * {@linkcode ListenerMiddlewareInstance.stopListening stopListening} call.
2560 *
2561 * @returns A pre-typed `stopListening` with the state, dispatch and extra types already defined.
2562 *
2563 * @example
2564 * ```ts
2565 * import { createListenerMiddleware } from '@reduxjs/toolkit'
2566 *
2567 * const listenerMiddleware = createListenerMiddleware()
2568 *
2569 * export const stopAppListening = listenerMiddleware.stopListening.withTypes<
2570 * RootState,
2571 * AppDispatch,
2572 * ExtraArguments
2573 * >()
2574 * ```
2575 *
2576 * @template OverrideStateType - The specific type of state the middleware listener operates on.
2577 * @template OverrideDispatchType - The specific type of the dispatch function.
2578 * @template OverrideExtraArgument - The specific type of the extra object.
2579 *
2580 * @since 2.1.0
2581 */
2582 withTypes: <OverrideStateType extends StateType, OverrideDispatchType extends Dispatch = ThunkDispatch<OverrideStateType, unknown, UnknownAction>, OverrideExtraArgument = unknown>() => TypedStopListening<OverrideStateType, OverrideDispatchType, OverrideExtraArgument>;
2583};
2584/**
2585 * Internal Types
2586 */
2587/** @internal An single listener entry */
2588type ListenerEntry<State = unknown, DispatchType extends Dispatch = Dispatch> = {
2589 id: string;
2590 effect: ListenerEffect<any, State, DispatchType>;
2591 unsubscribe: () => void;
2592 pending: Set<AbortController>;
2593 type?: string;
2594 predicate: ListenerPredicate<UnknownAction, State>;
2595};
2596/**
2597 * Utility Types
2598 */
2599/** @public */
2600type GuardedType<T> = T extends (x: any, ...args: any[]) => x is infer T ? T : never;
2601/** @public */
2602type ListenerPredicateGuardedActionType<T> = T extends ListenerPredicate<infer ActionType, any> ? ActionType : never;
2603
2604/**
2605 * @public
2606 */
2607declare const addListener: TypedAddListener<unknown>;
2608/**
2609 * @public
2610 */
2611declare const clearAllListeners: ActionCreatorWithoutPayload<"listenerMiddleware/removeAll">;
2612/**
2613 * @public
2614 */
2615declare const removeListener: TypedRemoveListener<unknown>;
2616/**
2617 * @public
2618 */
2619declare const createListenerMiddleware: <StateType = unknown, DispatchType extends Dispatch<Action> = ThunkDispatch<StateType, unknown, UnknownAction>, ExtraArgument = unknown>(middlewareOptions?: CreateListenerMiddlewareOptions<ExtraArgument>) => ListenerMiddlewareInstance<StateType, DispatchType, ExtraArgument>;
2620
2621type MiddlewareApiConfig = {
2622 state?: unknown;
2623 dispatch?: Dispatch;
2624};
2625type GetDispatchType<MiddlewareApiConfig> = MiddlewareApiConfig extends {
2626 dispatch: infer DispatchType;
2627} ? FallbackIfUnknown<DispatchType, Dispatch> : Dispatch;
2628type AddMiddleware<State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>> = {
2629 (...middlewares: Middleware<any, State, DispatchType>[]): void;
2630 withTypes<MiddlewareConfig extends MiddlewareApiConfig>(): AddMiddleware<GetState<MiddlewareConfig>, GetDispatchType<MiddlewareConfig>>;
2631};
2632type WithMiddleware<State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>> = BaseActionCreator<Middleware<any, State, DispatchType>[], 'dynamicMiddleware/add', {
2633 instanceId: string;
2634}> & {
2635 <Middlewares extends Middleware<any, State, DispatchType>[]>(...middlewares: Middlewares): PayloadAction<Middlewares, 'dynamicMiddleware/add', {
2636 instanceId: string;
2637 }>;
2638 withTypes<MiddlewareConfig extends MiddlewareApiConfig>(): WithMiddleware<GetState<MiddlewareConfig>, GetDispatchType<MiddlewareConfig>>;
2639};
2640interface DynamicDispatch {
2641 <Middlewares extends Middleware<any>[]>(action: PayloadAction<Middlewares, 'dynamicMiddleware/add'>): ExtractDispatchExtensions<Middlewares> & this;
2642}
2643type DynamicMiddleware<State = unknown, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>> = Middleware<DynamicDispatch, State, DispatchType>;
2644type DynamicMiddlewareInstance<State = unknown, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>> = {
2645 middleware: DynamicMiddleware<State, DispatchType>;
2646 addMiddleware: AddMiddleware<State, DispatchType>;
2647 withMiddleware: WithMiddleware<State, DispatchType>;
2648 instanceId: string;
2649};
2650
2651declare const createDynamicMiddleware: <State = any, DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>>() => DynamicMiddlewareInstance<State, DispatchType>;
2652
2653/**
2654 * Adapted from React: https://github.com/facebook/react/blob/master/packages/shared/formatProdErrorMessage.js
2655 *
2656 * Do not require this module directly! Use normal throw error calls. These messages will be replaced with error codes
2657 * during build.
2658 * @param {number} code
2659 */
2660declare function formatProdErrorMessage(code: number): string;
2661
2662export { 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 AsyncThunkConfig, type AsyncThunkDispatchConfig, type AsyncThunkOptions, type AsyncThunkPayloadCreator, type AsyncThunkPayloadCreatorReturnValue, type AsyncThunkReducers, 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, type WithSlicePreloadedState, 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 };
Note: See TracBrowser for help on using the repository browser.