【发布时间】:2018-01-02 12:19:53
【问题描述】:
我有一个使用 React 和 Redux 的 TypeScript 项目,我正在尝试添加一些中间件功能。我开始从 Redux 的示例中实现一个,如下所示:
// ---- middleware.ts ----
export type MiddlewareFunction = (store: any) => (next: any) => (action: any) => any;
export class MyMiddleWare {
public static Logger: MiddlewareFunction = store => next => action => {
// Do stuff
return next(action);
}
}
// ---- main.ts ----
import * as MyMiddleware from "./middleware";
const createStoreWithMiddleware = Redux.applyMiddleware(MyMiddleWare.Logger)(Redux.createStore);
上面的工作很好,但由于这是 TypeScript,我想让它成为强类型,理想情况下使用 Redux 定义的类型,这样我就不必重新发明和维护自己的类型。所以,这里是我的 index.d.ts 文件中的相关摘录:
// ---- index.d.ts from 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>;
}
我正试图弄清楚如何将这些类型带入我的 Logger 方法,但我运气不佳。在我看来,这样的事情应该可以工作:
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;
// Do stuff
return next(action);
};
}
但是我得到了这个错误:
错误 TS2322:类型 '(api: MiddlewareAPI) => (next: Dispatch) => (action: Action) => Action' 不可分配给类型 'Middleware'。
参数 'api' 和 'api' 的类型不兼容。
类型“MiddlewareAPI”不可分配给类型“MiddlewareAPI”。
类型“S”不可分配给类型“MyStore”。
我看到在类型定义中声明了 泛型,但我尝试了很多不同的组合,但我似乎无法弄清楚如何将其指定为 MyStore 以便将其识别为泛型类型在其余的声明中。例如,根据声明 api.getState() 应该返回一个 MyStore 对象。当然,同样的想法也适用于动作类型 。
【问题讨论】:
-
您有没有找到好的解决方案?使用类而不是函数?
标签: typescript redux