首页 > 解决方案 > 如何修复 redux-observable 参数'action$'隐式具有'any'类型

问题描述

我正在尝试实现 TS 史诗功能,但“action$”需要有一些不同的隐式类型,我找不到这种类型的函数的工作示例......

我制作的功能很好,但我无法修复任何类型的 TS 错误。

export const fetchSettingsEpic = action$ => action$.pipe(
  ofType(types.UPDATE_INITIAL_SETTINGS),
  mergeMap(action =>
    ajax.getJSON(url).pipe(
      map((response: Settings) => 
actions.updateInitialSuccess(response)),
      catchError(error => of(actions.updateInitialError(error))),
    ),
  ),
);

该功能非常简单,但我该如何解决“参数'action$'隐含的'any'类型。” 错误?

重要的!点告诉我关闭“noImplicitAny”:true,或者不要检查这部分代码)

标签: reactjstypescriptredux-observable

解决方案


不要关机noImplicityAny。你是对的,你不应该!

您应该做的是,声明参数的类型,即ActionsObservable<T>. 其中 T 应该是动作的类型。

例子:

export enum SettingsActionTypes {
   FETCH: "settings/fetch",
   FETCH_SUCCESS: "settings/fetchSuccess"
}

export function fetch(): IFetchAction {
   return {
       type: SettingsActionTypes.FETCH
   };
}

export interface IFetchAction {
   type: SettingsActionTypes.FETCH;
}

export interface IFetchSuccessAction {
   type: SettingsActionTypes.FETCH_SUCCESS;
}

export type SettingsAction = IFetchAction | IFetchSuccessAction;

然后在你的史诗中,你可以这样写:

import {
   ActionsObservable,
   StateObservable
} from 'redux-observable';

export const fetchSettingsEpic = (action$: ActionsObservable<SettingsAction>) =>
      action$.ofType(SettingsActionTypes.FETCH).mergeMap(...do your stuff here...)

此外,如果您需要访问史诗中的状态,则可能必须使用第二个参数 state$,其类型为StatesObservable<T>. 其中 T 是定义整个 redux 状态结构的接口。


推荐阅读