首页 > 解决方案 > Unknown not assignable to type:Redux Observable 中的 Typescript 错误

问题描述

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

'OperatorFunction<ITodo[], Action<{ params: { url: string; 类型的参数 }; } & { 结果:{ 待办事项:ITodo[]; }; }>>' 不能分配给 'OperatorFunction<unknown, Action<{ params: { url: string; 类型的参数。}; } & { 结果:{ 待办事项:ITodo[]; }; }>>'。类型“未知”不可分配给类型“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 }))
      )
    )
  );

标签: typescriptreduxredux-observable

解决方案


请检查AjaxCreationMethod接口:

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

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

更改您的代码如下:

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

推荐阅读