【问题标题】:Unknown not assignable to type: Typescript Error in Redux ObservableUnknown not assignable to type:Redux Observable 中的 Typescript 错误
【发布时间】:2021-06-08 03:56:09
【问题描述】:

我在 Redux Observable 中收到以下错误。 我该如何解决这个问题?

类型参数 'OperatorFunction>' 不能分配给类型为 'OperatorFunction>'。 类型 'unknown' 不可分配给类型 'ITodo[]'.ts(2345)

export interface ITodo {
  id: number;
  title: string;
}

interface IPayloadAction extends Action {
  type: string;
  payload?: any;
}

const todoFetchEpic: Epic<IPayloadAction> = (actions$) =>
  actions$.pipe(
    ofType(todoActions.fetch.started.type),
    mergeMap((action: IPayloadAction) =>
      concat(
        of(todoActions.loading({ isLoading: true })),
        ajax.getJSON(action.payload.url).pipe(
          map((todos: ITodo[]) =>
            todoActions.fetch.done({
              params: action.payload.url,
              result: {todos}
            })
          ),
          catchError((_) =>
            of(
              todoActions.fetch.failed({
                params: action.payload.url,
                error: { hasError: true },
              })
            )
          )
        ),
        of(todoActions.loading({ isLoading: false }))
      )
    )
  );

【问题讨论】:

    标签: typescript redux redux-observable


    【解决方案1】:

    请查看AjaxCreationMethod接口:

    export interface AjaxCreationMethod {
        // ... other methods ...
        getJSON<T>(url: string, headers?: Object): Observable<T>;
    }
    

    您可以看到,对于getJSON,您可以为响应指定泛型类型。 没有它,编译器就无法知道返回数据的形状,并假定为unknown。

    如下修改你的代码:

    ajax.getJSON<ITodo[]>(action.payload.url)
    

    【讨论】:

      猜你喜欢
      • 2022-01-26
      • 2023-02-25
      • 2022-12-02
      • 1970-01-01
      • 2020-07-29
      • 2022-09-22
      • 2023-02-15
      • 2020-10-02
      • 1970-01-01
      相关资源
      最近更新 更多