【发布时间】:2019-10-23 11:58:59
【问题描述】:
如何使用call()设置函数的类型?
我有这个功能:
export function apiFetch<T>(url: string): Promise<T> {
return fetch(url).then(response =>
{
if (!response.ok) throw new Error(response.statusText)
return response.json().then(data => data as T);
}
)
}
这个函数可以这样使用:
let resp = await apiFetch<ServerResponse>("http://localhost:51317/Task");
通过使用上述代码中的函数,resp 是正确的字符串类型。所以智能感知为我提供了ServerResponse 接口的所有属性。
但是,此函数必须在来自 redux-saga 的工作人员内部调用,这不允许异步函数:
function* refreshTaskSaga():any {
yield takeEvery("TASK_REFRESH", workerRefreshTaskSaga);
}
function* workerRefreshTaskSaga() {
//I need to call the function here
}
我尝试使用 yield + call 来调用它,正如redux-saga 文档所说:
a) let resp = yield call(apiFetch, "http://localhost:51317/Task");
b) let resp = yield call(apiFetch<ServerResponse>, "http://localhost:51317/Task");
第一个选项,按预期执行函数,但是resp 具有any 类型。
第二个选项给我一个异常。
No overload matches this call.
The last overload gave the following error.
Argument of type 'boolean' is not assignable to parameter of type '{ context: unknown; fn: (this: unknown, ...args: any[]) => any; }'.ts(2769)
effects.d.ts(499, 17): The last overload is declared here.
知道调用它的正确语法并且不会丢失类型吗?
【问题讨论】:
-
call来自哪里? -
我的错误。我要更新这个问题。
Call来自redux-saga
标签: typescript call redux-saga yield