Typescript: How to type the Dispatch in Redux
I got a bit further!
Dispatch is an event function, so got this to work:
interface IAllAssets {
type: IActions['GET_ALL_ASSETS'];
assets?: IAsset[];
loading: boolean;
}
// ACTIONS
// Fetch assets from Nomics API V1.
export const fetchAllAssets = () => (dispatch: (arg: IAllAssets) => (IAllAssets)) =>
{
dispatch(actionGetAllAssets());
return fetchAll([getPrices(), getAvailableSupply()]).then((responses) =>
dispatch(actionSetAllAssets(formatAssets(responses))));
}
However I'd still like to create a dispatch
type
, something like:
interface IAllAssetsDispatch {
dispatch: (arg: IAllAssets) => (IAllAssets)
}
export const fetchAllAssets = () => (dispatch: IAllAssetsDispatch) => {
But this produces the same lacks a call signature error.
GOT IT!
Forgot about type
that's what I needed to use instead of interface
for functions:
type DispatchAllAssets = (arg: IAllAssets) => (IAllAssets);
type DispatchMarketPrices = (arg: ISetMarket) => (ISetMarket);
type DispatchAddCoin = (arg: ICoinPortfolio) => (ICoinPortfolio);
type DispatchAddCoins = (arg: ICoinsPortfolio) => (ICoinsPortfolio);
// ACTIONS
// Fetch assets from Nomics API V1.
export const fetchAllAssets = () => (dispatch: DispatchAllAssets) => {
dispatch(actionGetAllAssets());
return fetchAll([getPrices(), getAvailableSupply()]).then((responses) =>
dispatch(actionSetAllAssets(formatAssets(responses))));
}
// Fetch USD, USDC & USDT markets to filter out Exchange List.
export const fetchMarketPrices = (asset: string) => (dispatch: DispatchMarketPrices) => {
dispatch(actionGetMarketPrices);
return getMarkets().then((res) => {
if (res && res.marketUSD && res.marketUSDC && res.marketUSDT) {
const exchangesForAsset = combineExchangeData(asset, res);
return dispatch(actionSetMarketPrices(exchangesForAsset));
}
else {
return dispatch(actionSetMarketPrices([]));
}
});
}
The Redux typings have a generic Dispatch<A>
type you can use, where A
is the type of action.
export const fetchAllAssets = () => (dispatch: Dispatch<IGetAllAssets | ISetAllAssets>) => {
// ...
}