#StackBounty: #javascript #reactjs #typescript #react-redux #redux-middleware How to implement a redux middleware class in TypeScript

Bounty: 50

According to the typescript definition of Redux, those interfaces should be implemented to make a middelware:

/* middleware */

export interface MiddlewareAPI<D extends Dispatch = Dispatch, S = any> {
  dispatch: D
  getState(): S

 * A middleware is a higher-order function that composes a dispatch function
 * to return a new dispatch function. It often turns async actions into
 * actions.
 * Middleware is composable using function composition. It is useful for
 * logging actions, performing side effects like routing, or turning an
 * asynchronous API call into a series of synchronous actions.
 * @template DispatchExt Extra Dispatch signature added by this middleware.
 * @template S The type of the state supported by this middleware.
 * @template D The type of Dispatch of the store where this middleware is
 *   installed.
export interface Middleware<
  DispatchExt = {},
  S = any,
  D extends Dispatch = Dispatch
> {
  (api: MiddlewareAPI<D, S>): (
    next: Dispatch<AnyAction>
  ) => (action: any) => any

I tried this:

import { Middleware, Dispatch, AnyAction, MiddlewareAPI } from 'redux';
import { AppState } from 'AppState';

class MiddlewareBase implements Middleware<{}, AppState, Dispatch<AnyAction>> {
  constructor() {
    return (api: MiddlewareAPI<Dispatch<AnyAction>, AppState>) => 
        (next: Dispatch<AnyAction>) =>
           (action: AnyAction) =>
                 // TODO: Do something before calling the next middleware.
                 return next(action);

export default MiddlewareBase;

But the compiler complains about this:

  Type 'MiddlewareBase' provides no match for the signature '(api: MiddlewareAPI<Dispatch<AnyAction>, AppState>): (next: Dispatch<AnyAction>) => (action: any) => any' 


It should be a class, not a function. I made a base class so I can inherit them later.

Get this bounty!!!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.