UNPKG

@reduxjs/toolkit

Version:

The official, opinionated, batteries-included toolset for efficient Redux development

357 lines (356 loc) 18.2 kB
import { Middleware, Reducer, ReducersMapObject, Action, AnyAction, StoreEnhancer, Store, DeepPartial } from "redux"; import { EnhancerOptions as DevToolsOptions } from "redux-devtools-extension"; import { ThunkDispatch } from "redux-thunk"; import { Draft } from "immer"; /** * Returns true if the passed value is "plain", i.e. a value that is either * directly JSON-serializable (boolean, number, string, array, plain object) * or `undefined`. * * @param val The value to check. */ declare function isPlain(val: any): boolean; interface NonSerializableValue { keyPath: string; value: unknown; } declare function findNonSerializableValue(value: unknown, path?: ReadonlyArray<string>, isSerializable?: (value: unknown) => boolean, getEntries?: (value: unknown) => [string, any][]): NonSerializableValue | false; /** * Options for `createSerializableStateInvariantMiddleware()`. */ interface SerializableStateInvariantMiddlewareOptions { /** * The function to check if a value is considered serializable. This * function is applied recursively to every value contained in the * state. Defaults to `isPlain()`. */ isSerializable?: (value: any) => boolean; /** * The function that will be used to retrieve entries from each * value. If unspecified, `Object.entries` will be used. Defaults * to `undefined`. */ getEntries?: (value: any) => [string, any][]; /** * An array of action types to ignore when checking for serializability, Defaults to [] */ ignoredActions?: string[]; } /** * Creates a middleware that, after every state change, checks if the new * state is serializable. If a non-serializable value is found within the * state, an error is printed to the console. * * @param options Middleware options. */ declare function createSerializableStateInvariantMiddleware(options?: SerializableStateInvariantMiddlewareOptions): Middleware; interface ThunkOptions<E = any> { extraArgument: E; } interface ImmutableStateInvariantMiddlewareOptions { isImmutable?: (value: any) => boolean; ignore?: string[]; } interface GetDefaultMiddlewareOptions { thunk?: boolean | ThunkOptions; immutableCheck?: boolean | ImmutableStateInvariantMiddlewareOptions; serializableCheck?: boolean | SerializableStateInvariantMiddlewareOptions; } /** * Returns any array containing the default middleware installed by * `configureStore()`. Useful if you want to configure your store with a custom * `middleware` array but still keep the default set. * * @return The default middleware used by `configureStore()`. */ declare function getDefaultMiddleware<S = any>(options?: GetDefaultMiddlewareOptions): Middleware<{}, S>[]; declare type ConfigureEnhancersCallback = (defaultEnhancers: StoreEnhancer[]) => StoreEnhancer[]; /** * Options for `configureStore()`. */ interface ConfigureStoreOptions<S = any, A extends Action = AnyAction> { /** * A single reducer function that will be used as the root reducer, or an * object of slice reducers that will be passed to `combineReducers()`. */ reducer: Reducer<S, A> | ReducersMapObject<S, A>; /** * An array of Redux middleware to install. If not supplied, defaults to * the set of middleware returned by `getDefaultMiddleware()`. */ middleware?: Middleware<{}, S>[]; /** * Whether to enable Redux DevTools integration. Defaults to `true`. * * Additional configuration can be done by passing Redux DevTools options */ devTools?: boolean | DevToolsOptions; /** * The initial state, same as Redux's createStore. * You may optionally specify it to hydrate the state * from the server in universal apps, or to restore a previously serialized * user session. If you use `combineReducers()` to produce the root reducer * function (either directly or indirectly by passing an object as `reducer`), * this must be an object with the same shape as the reducer map keys. */ preloadedState?: DeepPartial<S extends any ? S : S>; /** * The store enhancers to apply. See Redux's `createStore()`. * All enhancers will be included before the DevTools Extension enhancer. * If you need to customize the order of enhancers, supply a callback * function that will receive the original array (ie, `[applyMiddleware]`), * and should return a new array (such as `[applyMiddleware, offline]`). * If you only need to add middleware, you can use the `middleware` parameter instaead. */ enhancers?: StoreEnhancer[] | ConfigureEnhancersCallback; } /** * A Redux store returned by `configureStore()`. Supports dispatching * side-effectful _thunks_ in addition to plain actions. */ interface EnhancedStore<S = any, A extends Action = AnyAction> extends Store<S, A> { dispatch: ThunkDispatch<S, any, A>; } /** * A friendly abstraction over the standard Redux `createStore()` function. * * @param config The store configuration. * @returns A configured Redux store. */ declare function configureStore<S = any, A extends Action = AnyAction>(options: ConfigureStoreOptions<S, A>): EnhancedStore<S, A>; declare type IsAny<T, True, False = never> = (True | False) extends (T extends never ? True : False) ? True : False; declare type IsUnknown<T, True, False = never> = unknown extends T ? IsAny<T, False, True> : False; declare type IsEmptyObj<T, True, False = never> = T extends any ? keyof T extends never ? IsUnknown<T, False, True> : False : never; /** * returns True if TS version is above 3.5, False if below. * uses feature detection to detect TS version >= 3.5 * * versions below 3.5 will return `{}` for unresolvable interference * * versions above will return `unknown` * */ declare type AtLeastTS35<True, False> = [True, False][IsUnknown<ReturnType<(<T>() => T)>, 0, 1>]; declare type IsUnknownOrNonInferrable<T, True, False> = AtLeastTS35<IsUnknown<T, True, False>, IsEmptyObj<T, True, False>>; /** * An action with a string type and an associated payload. This is the * type of action returned by `createAction()` action creators. * * @template P The type of the action's payload. * @template T the type used for the action type. * @template M The type of the action's meta (optional) * @template E The type of the action's error (optional) */ declare type PayloadAction<P = void, T extends string = string, M = never, E = never> = WithOptional<M, E, WithPayload<P, Action<T>>>; declare type PrepareAction<P> = ((...args: any[]) => { payload: P; }) | ((...args: any[]) => { payload: P; meta: any; }) | ((...args: any[]) => { payload: P; error: any; }) | ((...args: any[]) => { payload: P; meta: any; error: any; }); declare type ActionCreatorWithPreparedPayload<PA extends PrepareAction<any> | void, T extends string = string> = PA extends PrepareAction<infer P> ? WithTypePropertyAndMatch<(...args: Parameters<PA>) => PayloadAction<P, T, MetaOrNever<PA>, ErrorOrNever<PA>>, T, P, MetaOrNever<PA>, ErrorOrNever<PA>> : void; declare type ActionCreatorWithOptionalPayload<P, T extends string = string> = WithTypePropertyAndMatch<{ (payload?: undefined): PayloadAction<undefined, T>; <PT extends Diff<P, undefined>>(payload?: PT): PayloadAction<PT, T>; }, T, P | undefined>; declare type ActionCreatorWithoutPayload<T extends string = string> = WithTypePropertyAndMatch<() => PayloadAction<undefined, T>, T, undefined>; declare type ActionCreatorWithPayload<P, T extends string = string> = WithTypePropertyAndMatch<IsUnknownOrNonInferrable<P, <PT extends unknown>(payload: PT) => PayloadAction<PT, T>, <PT extends P>(payload: PT) => PayloadAction<PT, T>>, T, P>; /** * An action creator that produces actions with a `payload` attribute. */ declare type PayloadActionCreator<P = void, T extends string = string, PA extends PrepareAction<P> | void = void> = IfPrepareActionMethodProvided<PA, ActionCreatorWithPreparedPayload<PA, T>, IfMaybeUndefined<P, ActionCreatorWithOptionalPayload<P, T>, IfVoid<P, ActionCreatorWithoutPayload<T>, ActionCreatorWithPayload<P, T>>>>; /** * A utility function to create an action creator for the given action type * string. The action creator accepts a single argument, which will be included * in the action object as a field called payload. The action creator function * will also have its toString() overriden so that it returns the action type, * allowing it to be used in reducer logic that is looking for that action type. * * @param type The action type to use for created actions. * @param prepare (optional) a method that takes any number of arguments and returns { payload } or { payload, meta }. * If this is given, the resulting action creator will pass it's arguments to this method to calculate payload & meta. */ declare function createAction<P = void, T extends string = string>(type: T): PayloadActionCreator<P, T>; declare function createAction<PA extends PrepareAction<any>, T extends string = string>(type: T, prepareAction: PA): PayloadActionCreator<ReturnType<PA>['payload'], T, PA>; /** * Returns the action type of the actions created by the passed * `createAction()`-generated action creator (arbitrary action creators * are not supported). * * @param action The action creator whose action type to get. * @returns The action type used by the action creator. */ declare function getType<T extends string>(actionCreator: PayloadActionCreator<any, T>): T; declare type Diff<T, U> = T extends U ? never : T; declare type WithPayload<P, T> = T & { payload: P; }; declare type WithOptional<M, E, T> = T & ([M] extends [never] ? {} : { meta: M; }) & ([E] extends [never] ? {} : { error: E; }); declare type WithTypeProperty<MergeIn, T extends string> = { type: T; } & MergeIn; declare type WithMatch<MergeIn, T extends string, P, M = never, E = never> = { match(action: Action<unknown>): action is PayloadAction<P, T, M, E>; } & MergeIn; declare type WithTypePropertyAndMatch<MergeIn, T extends string, P, M = never, E = never> = WithTypeProperty<WithMatch<MergeIn, T, P, M, E>, T>; declare type IfPrepareActionMethodProvided<PA extends PrepareAction<any> | void, True, False> = PA extends (...args: any[]) => any ? True : False; declare type MetaOrNever<PA extends PrepareAction<any>> = ReturnType<PA> extends { meta: infer M; } ? M : never; declare type ErrorOrNever<PA extends PrepareAction<any>> = ReturnType<PA> extends { error: infer E; } ? E : never; declare type IfMaybeUndefined<P, True, False> = [undefined] extends [P] ? True : False; declare type IfVoid<P, True, False> = [void] extends [P] ? True : False; /** * Defines a mapping from action types to corresponding action object shapes. */ declare type Actions<T extends keyof any = string> = Record<T, Action>; /** * An *case reducer* is a reducer function for a speficic action type. Case * reducers can be composed to full reducers using `createReducer()`. * * Unlike a normal Redux reducer, a case reducer is never called with an * `undefined` state to determine the initial state. Instead, the initial * state is explicitly specified as an argument to `createReducer()`. * * In addition, a case reducer can choose to mutate the passed-in `state` * value directly instead of returning a new state. This does not actually * cause the store state to be mutated directly; instead, thanks to * [immer](https://github.com/mweststrate/immer), the mutations are * translated to copy operations that result in a new state. */ declare type CaseReducer<S = any, A extends Action = AnyAction> = (state: Draft<S>, action: A) => S | void; /** * A mapping from action types to case reducers for `createReducer()`. */ declare type CaseReducers<S, AS extends Actions> = { [T in keyof AS]: AS[T] extends Action ? CaseReducer<S, AS[T]> : void; }; /** * A utility function that allows defining a reducer as a mapping from action * type to *case reducer* functions that handle these action types. The * reducer's initial state is passed as the first argument. * * The body of every case reducer is implicitly wrapped with a call to * `produce()` from the [immer](https://github.com/mweststrate/immer) library. * This means that rather than returning a new state object, you can also * mutate the passed-in state object directly; these mutations will then be * automatically and efficiently translated into copies, giving you both * convenience and immutability. * * @param initialState The initial state to be returned by the reducer. * @param actionsMap A mapping from action types to action-type-specific * case redeucers. */ declare function createReducer<S, CR extends CaseReducers<S, any> = CaseReducers<S, any>>(initialState: S, actionsMap: CR): Reducer<S>; /** * An action creator atttached to a slice. * * @deprecated please use PayloadActionCreator directly */ declare type SliceActionCreator<P> = PayloadActionCreator<P>; interface Slice<State = any, CaseReducers extends SliceCaseReducerDefinitions<State, PayloadActions> = { [key: string]: any; }> { /** * The slice name. */ name: string; /** * The slice's reducer. */ reducer: Reducer<State>; /** * Action creators for the types of actions that are handled by the slice * reducer. */ actions: CaseReducerActions<CaseReducers>; caseReducers: SliceDefinedCaseReducers<CaseReducers, State>; } /** * Options for `createSlice()`. */ interface CreateSliceOptions<State = any, CR extends SliceCaseReducerDefinitions<State, any> = SliceCaseReducerDefinitions<State, any>> { /** * The slice's name. Used to namespace the generated action types. */ name: string; /** * The initial state to be returned by the slice reducer. */ initialState: State; /** * A mapping from action types to action-type-specific *case reducer* * functions. For every action type, a matching action creator will be * generated using `createAction()`. */ reducers: CR; /** * A mapping from action types to action-type-specific *case reducer* * functions. These reducers should have existing action types used * as the keys, and action creators will _not_ be generated. */ extraReducers?: CaseReducers<NoInfer<State>, any>; } declare type PayloadActions<Types extends keyof any = string> = Record<Types, PayloadAction>; declare type CaseReducerWithPrepare<State, Action extends PayloadAction> = { reducer: CaseReducer<State, Action>; prepare: PrepareAction<Action['payload']>; }; declare type SliceCaseReducerDefinitions<State, PA extends PayloadActions> = { [ActionType in keyof PA]: CaseReducer<State, PA[ActionType]> | CaseReducerWithPrepare<State, PA[ActionType]>; }; declare type IfIsReducerFunctionWithoutAction<R, True, False = never> = R extends (state: any) => any ? True : False; declare type IfIsCaseReducerWithPrepare<R, True, False = never> = R extends { prepare: Function; } ? True : False; declare type PayloadForReducer<R> = R extends (state: any, action: PayloadAction<infer P>) => any ? P : void; declare type PrepareActionForReducer<R> = R extends { prepare: infer Prepare; } ? Prepare : never; declare type ActionForReducer<R, S> = R extends (state: S, action: PayloadAction<infer P>) => S ? PayloadAction<P> : R extends { reducer(state: any, action: PayloadAction<infer P>): any; } ? PayloadAction<P> : unknown; declare type CaseReducerActions<CaseReducers extends SliceCaseReducerDefinitions<any, any>> = { [Type in keyof CaseReducers]: IfIsCaseReducerWithPrepare<CaseReducers[Type], ActionCreatorWithPreparedPayload<PrepareActionForReducer<CaseReducers[Type]>>, IfIsReducerFunctionWithoutAction<CaseReducers[Type], ActionCreatorWithoutPayload, PayloadActionCreator<PayloadForReducer<CaseReducers[Type]>>>>; }; declare type SliceDefinedCaseReducers<CaseReducers extends SliceCaseReducerDefinitions<any, any>, State = any> = { [Type in keyof CaseReducers]: CaseReducer<State, ActionForReducer<CaseReducers[Type], State>>; }; declare type NoInfer<T> = [T][T extends any ? 0 : never]; declare type SliceCaseReducersCheck<S, ACR> = { [P in keyof ACR]: ACR[P] extends { reducer(s: S, action?: { payload: infer O; }): any; } ? { prepare(...a: never[]): { payload: O; }; } : {}; }; declare type RestrictCaseReducerDefinitionsToMatchReducerAndPrepare<S, CR extends SliceCaseReducerDefinitions<S, any>> = { reducers: SliceCaseReducersCheck<S, NoInfer<CR>>; }; /** * A function that accepts an initial state, an object full of reducer * functions, and a "slice name", and automatically generates * action creators and action types that correspond to the * reducers and state. * * The `reducer` argument is passed to `createReducer()`. */ declare function createSlice<State, CaseReducers extends SliceCaseReducerDefinitions<State, any>>(options: CreateSliceOptions<State, CaseReducers> & RestrictCaseReducerDefinitionsToMatchReducerAndPrepare<State, CaseReducers>): Slice<State, CaseReducers>; export * from 'redux'; export { default as createNextState } from 'immer'; export { createSelector } from "reselect"; export { ConfigureEnhancersCallback, ConfigureStoreOptions, EnhancedStore, configureStore, PayloadAction, PrepareAction, ActionCreatorWithPreparedPayload, ActionCreatorWithOptionalPayload, ActionCreatorWithoutPayload, ActionCreatorWithPayload, PayloadActionCreator, createAction, getType, Actions, CaseReducer, CaseReducers, createReducer, SliceActionCreator, Slice, CreateSliceOptions, createSlice, isPlain, findNonSerializableValue, SerializableStateInvariantMiddlewareOptions, createSerializableStateInvariantMiddleware, getDefaultMiddleware };