我正在尝试使用 fp-ts 和 redux-observable 来构建一些处理某些 api 请求的史诗。我遇到了 fp-ts-rxjs/ObservableEither#fold 的问题如果我不将操作转换为 AnyAction
类型,我会收到一个类型错误,指出这两种类型应该是相同的。
Type 'Observable<{ payload: { user: User<Attributes>; }; type: string; }>' is not assignable to type 'Observable<{ payload: { error: Error | null; }; type: string; }>'.
Type '{ payload: { user: User<Attributes>; }; type: string; }' is not assignable to type '{ payload: { error: Error | null; }; type: string; }'.
Types of property 'payload' are incompatible.
Property 'error' is missing in type '{ user: User<Attributes>; }' but required in type '{ error: Error | null; }'
我也尝试过使用 fp-ts-rxjs/ObservableEither#bimap因为它期望返回两种不同的类型。但是,这会导致运行时错误,指出操作不能具有未定义的类型。我也不确定那里到底发生了什么。
LoginSlice.ts
const loginSlice = createSlice({
name: 'login',
initialState,
reducers: {
loginSuccess (state, action: PayloadAction<{ user: User }>) {
state.loggedIn = true;
},
loginReset (state) {
state.error = null;
},
loginFail (state, action: PayloadAction<{ error: Error | null } >) {
state.error = action.payload.error;
}
}
});
LoginService.ts
const loginService = (credentials: LoginInfo): OE.ObservableEither<Error, User> => {
const { username, password } = credentials;
return OE.fromTaskEither(
TE.tryCatch(
async () => await User.logIn(username, password),
error => error as Error
)
);
};
LoginEpics.ts
export const loginEpic: Epic = (action$: ActionsObservable<AnyAction>) => action$.pipe(
filter(login.match),
mergeMap((action) =>
loginService(action.payload.credentials).pipe(
fold(
(error) => of(loginFail({ error }) as AnyAction),
(user) => of(loginSuccess({ user }) as AnyAction)
)
)
)
);
有没有办法避免将操作转换为AnyAction
?任何见解将不胜感激。
最佳答案
我不熟悉fp-ts-rxjs/ObservableEither
,但如果它们的fold
函数的定义与常规fp-ts
类似> 定义了折叠函数,我认为可以通过从传递到 fold
的一个或两个匿名函数指定精确的返回类型来解决您的问题。
当没有指定返回类型时,TypeScript 尝试从第一个函数推断返回类型,但不够聪明,没有意识到因为两个匿名函数返回不同的类型,所以折叠结果应该是两个返回类型的并集.
假设您有 LoginFailure
和 LoginSuccess
操作类型,没有 AnyAction
的折叠将如下所示:
fold(
(error): LoginFailure | LoginSuccess => of(loginFail({ error })),
(user): LoginFailure | LoginSuccess => of(loginSuccess({ user }))
)
这里我们指定返回类型应该是可能返回的操作的并集。
关于typescript - 如何正确输入 fp-ts ObservableEither#fold?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67890621/