我正在尝试为可用于AsyncActionCreators
对象的操作创建简写类型。
我创建了一个简单的函数,该函数带有一个React dispatch: Dispatch<T>
参数:
const fetchProfileAction = actionCreator.async<void, Profile, any>('FETCH_PROFILE');
// AsyncActionCreators<Params = void, Result = Profile, Error = any>;
type AsyncDispatch<A extends AsyncActionCreators<Params, Result, Error>, Params, Result, Error> = Dispatch<
ReturnType<A['started'] | A['done'] | A['failed']>
>;
export const fetchProfile = (
dispatch: AsyncDispatch<typeof fetchProfileAction, void, Profile, any>,
) => async () => {
dispatch(fetchProfileAction.started());
try {
dispatch(fetchProfileAction.done({ result: (await api.get<Profile>('/profile')).data }));
} catch (e) {
dispatch(fetchProfileAction.failed(e));
}
};
目前的问题是我必须手动指定fetchProfileAction
中使用的类型:
AsyncDispatch<typeof fetchProfileAction, void, Profile, any>
是否可以简化并以自动解决的AsyncDispatch<typeof fetchProfileAction>
类型的Params
Result
,Error
类型到类似AsyncActionCreators
的东西?>
答案 0 :(得分:1)
您可以使用type inference in conditional types:
type AsyncDispatch<A> = A extends AsyncActionCreators<infer Params, infer Result, infer Error>
? Dispatch<ReturnType<A['started'] | A['done'] | A['failed']>>
: never;