Tengo una función de ayuda que usa fetch para obtener datos de una API:
const callApi = (endpoint: string, method = 'GET', body?: string): Promise<Response> => { // decide if url is dev or prod const url = getUrl() const headers = new Headers() headers.set('infinote-token', store.infinoteToken as string) const initObject = { headers: headers, method: method, body: method === 'POST' ? body : undefined } return fetch(`${url}${endpoint}`, initObject) .then(r => { if (r.ok) { apiIsOnline() } else if (r.status === 403) { store.needToSetToken = true apiIsOnline() } else { apiIsOffline() throw Error(r.statusText) } }) .catch((reason) => { log.debug(`API call rejected because: ${reason}`) return Promise.reject() }) }Genera un error TS:
TS2322: Type 'Promise<void | Response>' is not assignable to type 'Promise<Response>'. Type 'void | Response' is not assignable to type 'Response'. Type 'void' is not assignable to type 'Response'. ¿De dónde viene este requisito para Promise<void> ?
Tengo entendido que fetch devuelve una Promise<Response> :
La promesa se resuelve en el objeto Response que representa la respuesta a su solicitud.
Sí, fetch devuelve Promise<Response> . Pero está manejando este resultado con .then(r => ...) Esta r es la Response que obtiene de fetch . El resultado general de una cadena de promesa foo().then().then()... es el resultado del último then() . Pero su controlador then() no devuelve nada (bueno, técnicamente sí devuelve un Promise<void> ). Por lo tanto, el resultado general de su fetch(...).then(...) es Promise<void> . Si solo desea pasar a través de la Respuesta, agregue una return r a su then()
return fetch(`${url}${endpoint}`, initObject) .then(r => { if (r.ok) { apiIsOnline() } else if (r.status === 403) { store.needToSetToken = true apiIsOnline() } else { apiIsOffline() throw Error(r.statusText) } return r; })