未知不可分配给类型:Redux Observable 中的 Typescript 错误
Unknown not assignable to type: Typescript Error in Redux Observable
我在 Redux Observable 中收到以下错误。
我该如何解决这个问题?
'OperatorFunction<ITodo[], Action<{ params: { url: string; }; } & { result: { todos: ITodo[]; }; }>>' 类型的参数不能分配给 'OperatorFunction<unknown, Action<{ params: { url: string; }; } & { result: { todos: ITodo[]; }; }>>' 类型的参数。
类型 '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 }))
)
)
);
请检查AjaxCreationMethod
接口:
export interface AjaxCreationMethod {
// ... other methods ...
getJSON<T>(url: string, headers?: Object): Observable<T>;
}
您可以看到,对于 getJSON
,您可以为响应指定通用类型。
没有它,编译器就不知道返回数据的形状,并假定 unknown
.
按如下方式更改您的代码:
ajax.getJSON<ITodo[]>(action.payload.url)
我在 Redux Observable 中收到以下错误。 我该如何解决这个问题?
'OperatorFunction<ITodo[], Action<{ params: { url: string; }; } & { result: { todos: ITodo[]; }; }>>' 类型的参数不能分配给 'OperatorFunction<unknown, Action<{ params: { url: string; }; } & { result: { todos: ITodo[]; }; }>>' 类型的参数。 类型 '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 }))
)
)
);
请检查AjaxCreationMethod
接口:
export interface AjaxCreationMethod {
// ... other methods ...
getJSON<T>(url: string, headers?: Object): Observable<T>;
}
您可以看到,对于 getJSON
,您可以为响应指定通用类型。
没有它,编译器就不知道返回数据的形状,并假定 unknown
.
按如下方式更改您的代码:
ajax.getJSON<ITodo[]>(action.payload.url)