title: How do you create strongly typed redux middleware in TypeScript from Redux's type definitions?
body: <p>I have a TypeScript project that uses React and Redux and I'm trying to add some middleware functions.  I got started by implementing one from Redux's samples like so:</p>
  
  <pre><code>// ---- middleware.ts ----
  export type MiddlewareFunction = (store: any) =&gt; (next: any) =&gt; (action: any) =&gt; any;
  
  export class MyMiddleWare {
      public static Logger: MiddlewareFunction = store =&gt; next =&gt; action =&gt; {
          // Do stuff
          return next(action);
      }
  }
  
  // ---- main.ts ---- 
  import * as MyMiddleware from "./middleware";
  
  const createStoreWithMiddleware = Redux.applyMiddleware(MyMiddleWare.Logger)(Redux.createStore);
  </code></pre>
  
  <p>The above works just fine but since this is TypeScript I'd like to make it strongly-typed, ideally using the types defined by Redux so I don't have to reinvent and maintain my own.  So, here are the relevant excerpts from my index.d.ts file for Redux:</p>
  
  <pre><code>// ---- index.d.ts from Redux ----
  export interface Action {
      type: any;
  }
  
  export interface Dispatch&lt;S&gt; {
      &lt;A extends Action&gt;(action: A): A;
  }
  
  export interface MiddlewareAPI&lt;S&gt; {
      dispatch: Dispatch&lt;S&gt;;
      getState(): S;
  }
  
  export interface Middleware {
      &lt;S&gt;(api: MiddlewareAPI&lt;S&gt;): (next: Dispatch&lt;S&gt;) =&gt; Dispatch&lt;S&gt;;
  }
  </code></pre>
  
  <p>I'm trying to figure out how to bring those types into my Logger method but I'm not having much luck.  It seems to me that something like this ought to work:</p>
  
  <pre><code>interface MyStore {
      thing: string;
      item: number;
  }
  
  interface MyAction extends Action {
      note: string;
  }
  
  export class MyMiddleWare {
      public static Logger: Middleware = (api: MiddlewareAPI&lt;MyStore&gt;) =&gt; (next: Dispatch&lt;MyStore&gt;) =&gt; (action: MyAction) =&gt; {
          const currentState: MyStore = api.getState();
          const newNote: string = action.note;
          // Do stuff
          return next(action);
      };
  }
  </code></pre>
  
  <p>but instead I get this error:</p>
  
  <p><em>Error TS2322: Type '(api: MiddlewareAPI) => (next: Dispatch) => (action: Action) => Action' is not assignable to type 'Middleware'.<br>
    Types of parameters 'api' and 'api' are incompatible.<br>
      Type 'MiddlewareAPI' is not assignable to type 'MiddlewareAPI'.<br>
        Type 'S' is not assignable to type 'MyStore'.</em></p>
  
  <p>I see the &lt;S&gt; generic declared in the type definition, but I've tried a lot of different combinations and I can't seem to figure out how to specify it as MyStore so that it is recognized as the generic type in the rest of the declarations.  For example, according to the declaration api.getState() should return a MyStore object.  Same thinking applies to the action type &lt;A&gt;, of course.</p>