使用Typescript创建Redux中间件

时间:2017-12-16 21:57:56

标签: reactjs typescript redux react-redux

我希望在我的redux中间件中获得带类型检查的状态。使用Typescript 2.6.2,我可以很容易地创建一个redux中间件,如下所示:

import { Middleware, MiddlewareAPI, Dispatch } from 'redux';
import { IState } from '~/shared/rootReducer';

const logger: Middleware = 
    <S>({ getState }: MiddlewareAPI<S>) => (next: Dispatch<S>) => (action: any) => {
    console.log(action);
    next(action);
};

export default logger;

我想使用类型检查进行const { songs } = getState();,但我无法推断S的类型为IState,这是我的根减速器的类型。尝试const logger: Middleware = <S extends IState>会给我这个错误:

Type 'S' is not assignable to type 'IState'.

我也尝试过创建一个返回state is IState的方法,但也失败了。我可以这样做:

const state = <IState><any>getState();

但我真的不愿意。

1 个答案:

答案 0 :(得分:1)

据我理解版本redux@^3.7.2中的TS,不可能在中间件中键入您的状态。以下是一种解决方法,您需要在applyMiddlewares中投射中间件。

Middleware

import { MiddlewareAPI, Dispatch, Action } from 'redux';
import { IState } from '~/shared/rootReducer';

const logger = (api: MiddlewareAPI<IState>) => {
  const { songs } = api.getState();
  return (next: Dispatch<IState>) => (action: Action) => {
    return next(action);
  };
};

export default logger;

logger不属于Middleware类型,因为它不是S的通用,因为我们通过指定具体的<S>来关闭IStateapplyMiddleware因此需要Middleware[]

Setup

applyMiddleware(...middlewares as Middleware[]);