我正在使用react和redux observate创建一个应用程序。我是新手,我正在尝试创建一个史诗来执行用户登录。我的史诗如下:export const loginUserEpic = (action$: ActionsObservable<Action>) => action$.pipe( ofType<LoginAction>(LoginActionTypes.LOGIN_ACTION), switchMap((action: LoginAction) => ajax({ url, method: 'POST', headers: { 'Content-Type': 'application/json' }, body: { email: action.payload.username, password: action.payload.password }, }).pipe( map((response: AjaxResponse) => loginSuccess(response.response.token)), catchError((error: Error) => of(loginFailed(error))), ), ), );问题是,我在这一行中遇到一个typescript错误:ofType<LoginAction>(LoginActionTypes.LOGIN_ACTION)这样说:Argument of type '(source: Observable<LoginAction>) => Observable<LoginAction>' is not assignable to parameter of type 'OperatorFunction<Action<any>, LoginAction>'. Types of parameters 'source' and 'source' are incompatible. Type 'Observable<Action<any>>' is not assignable to type 'Observable<LoginAction>'. Type 'Action<any>' is not assignable to type 'LoginAction'. Property 'payload' is missing in type 'Action<any>'.我的行动如下:export enum LoginActionTypes { LOGIN_ACTION = 'login', LOGIN_SUCCESS_ACTION = 'login-sucesss', LOGIN_FAILED_ACTION = 'login-failed',}export interface LoginAction extends Action { type: LoginActionTypes.LOGIN_ACTION; payload: { username: string; password: string; };}export function login(username: string, password: string): LoginAction { return { type: LoginActionTypes.LOGIN_ACTION, payload: { username, password }, };}export interface LoginSuccessAction extends Action { type: LoginActionTypes.LOGIN_SUCCESS_ACTION; payload: { loginToken: string; };}export function loginSuccess(loginToken: string): LoginSuccessAction { return { type: LoginActionTypes.LOGIN_SUCCESS_ACTION, payload: { loginToken }, };}export interface LoginFailedAction extends Action { type: LoginActionTypes.LOGIN_FAILED_ACTION; payload: { error: Error; };}export function loginFailed(error: Error): LoginFailedAction { return { type: LoginActionTypes.LOGIN_FAILED_ACTION, payload: { error }, };}export type LoginActions = LoginAction | LoginSuccessAction | LoginFailedAction;如果不在epic上使用any类型,我如何解决这个问题? 最佳答案 ofType提供的redux-observable运算符不是区分并集类型的最佳方法。一个更好的方法是使用提供的isOfType函数。import { filter } from 'rxjs/operators';import { isOfType } from 'typesafe-actions';首先,让我们告诉typescript应用程序中可能使用的操作。您的操作流不应定义为typesafe-actions,而应定义为您的操作流:ActionsObservable<Action>。export const loginUserEpic = (action$: ActionsObservable<LoginActions>) =>现在我们可以将ActionsObservable<LoginActions>谓词与isOfType运算符一起使用。替换为:ofType<LoginAction>(LoginActionTypes.LOGIN_ACTION)有了这个:filter(isOfType(LoginActionTypes.LOGIN_ACTION))流下传递的操作将被正确识别为filter。
08-28 09:09