I have a TypeScript project that uses React and Redux, and I'm trying to add some middleware features. I started using one of the Redux examples:
export type MiddlewareFunction = (store: any) => (next: any) => (action: any) => any;
export class MyMiddleWare {
public static Logger: MiddlewareFunction = store => next => action => {
return next(action);
}
}
import * as MyMiddleware from "./middleware";
const createStoreWithMiddleware = Redux.applyMiddleware(MyMiddleWare.Logger)(Redux.createStore);
The above works fine, but since it is TypeScript, I would like to make it strongly typed, ideally using types defined by Redux, so I don't need to invent and maintain my own. So, here are the relevant excerpts from my index.d.ts file for Redux:
export interface Action {
type: any;
}
export interface Dispatch<S> {
<A extends Action>(action: A): A;
}
export interface MiddlewareAPI<S> {
dispatch: Dispatch<S>;
getState(): S;
}
export interface Middleware {
<S>(api: MiddlewareAPI<S>): (next: Dispatch<S>) => Dispatch<S>;
}
I'm trying to figure out how to cast these types to my Logger method, but I'm not very lucky. It seems to me that something like this should work:
interface MyStore {
thing: string;
item: number;
}
interface MyAction extends Action {
note: string;
}
export class MyMiddleWare {
public static Logger: Middleware = (api: MiddlewareAPI<MyStore>) => (next: Dispatch<MyStore>) => (action: MyAction) => {
const currentState: MyStore = api.getState();
const newNote: string = action.note;
return next(action);
};
}
but instead I get this error:
TS2322: '(api: MiddlewareAPI) = > (: ) = > (: ) = > ' 'Middleware'.
"api" "api" .
"MiddlewareAPI" "MiddlewareAPI".
'S' 'MyStore'.
<S> generic, , , , MyStore, . , api.getState() MyStore. <A> , .