Is there a way to specify the types of a function using call()
?
Consider this function:
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);
}
)
}
This function is typically used like this:
let resp = await apiFetch<ServerResponse>("http://localhost:51317/Task");
When used in the above manner, resp
correctly retains its string type. This enables Intellisense to offer all attributes of the ServerResponse
interface.
However, calling this function inside a worker from redux-saga
poses a challenge because async functions are not allowed:
function* refreshTaskSaga():any {
yield takeEvery("TASK_REFRESH", workerRefreshTaskSaga);
}
function* workerRefreshTaskSaga() {
//The function needs to be called here
}
I attempted to call it using yield + call, following redux-saga
documentation:
a) let resp = yield call(apiFetch, "http://localhost:51317/Task");
b) let resp = yield call(apiFetch<ServerResponse>, "http://localhost:51317/Task");
The first option executes the function correctly but assigns any
type to resp
.
The second option results in an exception being thrown.
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.
Can anyone provide insight into the correct syntax to maintain types when calling this function?