【发布时间】:2019-01-18 09:41:37
【问题描述】:
在使用 Typescript 3.2.2 和 typesafe-actions 3.0.0 时遇到问题。我在下面创建了一个示例来显示该问题。
基本上在我的 reducer 中,payload 没有在 action 上定义,因为我的一些操作属于 EmptyAction 类型,它没有定义 payload 属性。如果我将这些更改为空有效负载 ({}),则为所有操作定义payload,但现在payload 的类型不是基于操作的type 确定的(在减速器中)。
我相信我已经正确地关注了Mighty Tutorial。
工作示例:https://github.com/JoshMcCullough/react-ts-test
action-types.ts
export default {
GET_PROFILES_REQUEST: "GET_PROFILES_REQUEST",
GET_PROFILES_SUCCESS: "GET_PROFILES_SUCCESS",
GET_PROFILES_FAILURE: "GET_PROFILES_FAILURE",
};
actions.ts
import { action } from "typesafe-actions";
import { ApiErrorResponse } from "../../app/api/ApiErrorResponse";
import { Profile } from "../../app/models/Profile";
import ActionTypes from './action-types';
export const getProfilesRequest = () => action(ActionTypes.GET_PROFILES_REQUEST); // EmptyAction<string>
export const getProfilesSuccess = (profiles: Profile[]) => action(ActionTypes.GET_PROFILES_SUCCESS, { profiles }); // Action<string, { profiles: Profile[] }>
export const getProfilesFailure = (error: ApiErrorResponse) => action(ActionTypes.GET_PROFILES_FAILURE, { error }); // Action<string, { error: ApiErrorResponse }>
reducer.ts
import { ActionType, getType } from "typesafe-actions";
import * as Actions from './actions';
import { Profile } from "../../app/models/Profile";
// reducer
export type ProfileAction = ActionType<typeof Actions>;
export type State = {
profiles: Profile[];
errorMessage: string;
loading: boolean;
};
const INITIAL_STATE = {
profiles: [],
errorMessage: null,
loading: false,
};
export default (state: State = INITIAL_STATE, action: ProfileAction): State => {
switch (action.type) {
case getType(Actions.getProfilesRequest): return {
...state,
loading: true,
};
case getType(Actions.getProfilesSuccess): return {
...state,
profiles: action.payload.profiles,
// ERROR: Property 'payload' does not exist on type 'EmptyAction<string> | PayloadAction<string, { profiles: Profile[]; }> | PayloadAction<string, { error: ApiErrorResponse; }>'.
// Property 'payload' does not exist on type 'EmptyAction<string>'. [2339]
loading: false,
};
case getType(Actions.getProfilesRequest): return {
...state,
errorMessage: action.payload.error.message,
// ERROR: Property 'payload' does not exist on type 'EmptyAction<string> | PayloadAction<string, { profiles: Profile[]; }> | PayloadAction<string, { error: ApiErrorResponse; }>'.
// Property 'payload' does not exist on type 'EmptyAction<string>'. [2339]
loading: false,
};
default: return state;
}
};
【问题讨论】:
标签: reactjs typescript redux