javascript - Typescript:如何在 Redux 中键入 Dispatch
问题描述
例如我想在dispatch: any
这里删除:
export const fetchAllAssets = () => (dispatch: any) => {
dispatch(actionGetAllAssets);
return fetchAll([getPrices(), getAvailableSupply()]).then((responses) =>
dispatch(actionSetAllAssets(formatAssets(responses))));
}
我在上面调度了 2 个动作,actionsGetAllAssets
并且actionsSetAllassets
.
以下是两者的接口和 actionCreators:
// Interfaces
interface IActions {
GET_ALL_ASSETS: string;
SET_ALL_ASSETS: string;
GET_MARKET_PRICES: string;
SET_MARKET_PRICES: string;
ADD_COIN_PORTFOLIO: string;
ADD_COINS_PORTFOLIO: string;
UPDATE_COIN_PORTFOLIO: string;
REMOVE_COIN_PORTFOLIO: string;
}
interface IGetAllAssets {
type: IActions['GET_ALL_ASSETS'];
loading: boolean;
}
interface ISetAllAssets {
type: IActions['SET_ALL_ASSETS'];
assets: IAsset[];
loading: boolean;
}
// ACTION CREATORS
const actionGetAllAssets = () => ({
type: Actions.GET_ALL_ASSETS,
loading: true
});
const actionSetAllAssets = (data: any) => ({
type: Actions.SET_ALL_ASSETS,
assets: data,
loading: false
});
所以我尝试了以下方法:
export const fetchAllAssets = () => (dispatch: IGetAllAssets | ISetAllAssets) => {
console.log('fetchAllAssets', dispatch);
dispatch(actionGetAllAssets);
return fetchAll([getPrices(), getAvailableSupply()]).then((responses) =>
dispatch(actionSetAllAssets(formatAssets(responses))));
}
但是它会产生这个 Typescript 错误:
无法调用其类型缺少调用签名的表达式。输入'IGetAllAssets | ISetAllAssets' 没有兼容的调用 signatures.ts(2349)
想法?或者是否有不同的方式来输入调度事件?
解决方案
Redux 类型有一个Dispatch<A>
你可以使用的泛型类型,其中A
是 action 的类型。
export const fetchAllAssets = () => (dispatch: Dispatch<IGetAllAssets | ISetAllAssets>) => {
// ...
}
推荐阅读
- c++ - 我可以通过placement-new 覆盖一个const 对象吗?
- visual-studio - 无法在 Windows 10 中打开 VS 解决方案文件
- c# - 如何使用 xpath 选择 Textbox 节点的第一个 Value 节点?
- flutter - 错误:无法将参数类型“PointerEvent”分配给参数类型“PointerDownEvent”
- java - 使用 Optional 而不是嵌套 if else 的 Lambda 函数
- javascript - 如何使用回车键点击字体真棒(喜欢/不喜欢)图标?
- sql - 可选择运行派生表。使用“where 子句”或“连接条件”更快地排除数据
- python - Kivy,鼠标周围不透明,显示图片
- python - Microsoft-Graph:无法从 python 代码获取令牌:错误 SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED]
- python - 根据特定列的相等文本加入数据库