创建速记类型时重用扩展接口的通用类型

时间:2019-04-15 06:32:37

标签: javascript typescript generics typescript-typings

我正在尝试为可用于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 ResultError类型到类似AsyncActionCreators的东西?

1 个答案:

答案 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;