【发布时间】:2021-08-24 22:52:08
【问题描述】:
我正在使用 flow 并且我想让我的 reducer 更安全。我遇到了这个评论,它提出了一个我觉得很好并且适合我的代码库的解决方案: https://github.com/reduxjs/redux/issues/992#issuecomment-191152574
我正在尝试使用 %checks 关键字将其移植到流中,但它不起作用。
我的代码:
export type Action<T> = {
type: string,
payload: T,
};
interface ActionCreator<P> {
type: string;
(payload: P): Action<P>;
}
export function actionCreator<P>(type: string): ActionCreator<P> {
return Object.assign((payload: P) => ({ type, payload }), { type });
}
export function isActionOfType<P>(
action: Action<any>,
creator: ActionCreator<P>
): boolean %checks {
return action.type === creator.type;
}
每当我像这样在 reducer 函数中使用它时
(...)
case isActionOfType(action, getArticles):
// action.payload is still any
(...)
我做错了吗?是否有可能让这个打字稿解决方案流畅运行?还是我应该使用不同的方法?如果是,您有什么建议?
【问题讨论】:
标签: javascript typescript redux flowtype type-safety