有没有办法在Flow中创建一个类型'generator'?
在我的redux代码中,我有一个处理API操作的中间件。
export const updateUser = (user: User, changes: UserParams) => ({
user,
[CALL_API]: {
types: [
"UPDATE_USER_REQUEST",
"UPDATE_USER_SUCCESS",
"UPDATE_USER_FAILURE",
],
endpoint: `/users/${user.id}`,
method: "PATCH",
body: changes,
},
});
由于我的中间件是如何定义的,我知道这意味着我的Reducer需要响应三个动作,如下所示:
{
type: "UPDATE_USER_REQUEST",
user: { id: 1, ... },
}
{
type: "UPDATE_USER_SUCCESS",
user: { id: 1, name: 'Ben', ... },
response: { id: 1, name: 'Bill', ... // API Response Shape }
}
{
type: "UPDATE_USER_FAILURE",
user: { id: 1, ... },
status: 400 // API response code,
message: { email: 'Is already taken' // API Errors },
}
目前我必须手动输入这些动作形状的外观,以便我可以正确地在减速器中键入action
。
如果我提供成功和失败API响应的形状,是否有办法以编程方式为这三个操作生成动作类型?
E.g。
type APISuccessResponseType = {
user: User
}
type APIErrorResponseType = {
validationErrors: { [field: string]: string }
}
type UpdateUserActions = GENERATE_API_ACTION_TYPES(typeof updateUser, APISuccessResponse, APIErrorResponse)
我不知道如何填写GENERATE_API_ACTION_TYPES
,但它应该返回以下类型定义:
| {
type: "UPDATE_USER_REQUEST",
user: User,
}
| {
type: "UPDATE_USER_SUCCESS",
user: User,
response: APISuccessResponseType,
}
| {
type: "UPDATE_USER_FAILURE",
user,
status: 404 | 500,
message: APIErrorResponseType,
}