Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

190
Views
Texto mecanografiado: cambiar de axios a fetch está dando un error de tipo

Tengo un problema al cambiar de Axios a Fetch en los tipos esperados que se devuelven. Mi código original con Axios es el siguiente:

 private async getAccessType(): Promise<string> { const config: RequestInit = { method: "get", baseURL: SERVER_INFO.URL, url: '/getData', headers: { Authorization: this.token, "X-Api-key": SERVER.KEY } }; const response = await axios(config); const { library } = await response.data; return library; // result is "access" or "no-access" }

El resultado de la respuesta es JSON:

 { "library": "access", "name": { "first": "James" } }

así que solo lo estoy desestructurando y devolviendo la library en la función, que es una string .

Estoy tratando de cambiar para fetch ahora:

 import fetch, { RequestInit } from "node-fetch"; private async getAccessType(): Promise<string> { const baseURL: SERVER_INFO.URL; const config: RequestInit = { method: "get", headers: { Authorization: this.token, "X-Api-key": SERVER.KEY } }; const response = await fetch(`${baseURL}/getData`,config); const { library } = await response.json(); return library; }

y la línea const { library } = await response.data; me está dando un error de TS de que la Property 'library' does not exist on type 'unknown'.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

fetch.json() devuelve Promise<unknown> , TypeScript no le permite tomar una propiedad de unknown porque no sabe si existe en el objeto de respuesta, de ahí el error.

La propiedad 'biblioteca' no existe en el tipo 'desconocido'.

Puede enviar su respuesta a lo que espera de la solicitud.

 const { library } = await data.json() as { library: string };

En su caso, podría crear una interface para la respuesta esperada.

 // expected response interface IFetchRes { library: string; name: { first: string; } } // unknown => interpret as expected response const { library, name } = await data.json() as IFetchRes;
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!