Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

198
Vistas
Typescript: Switching from axios to fetch is giving a type error

I am having an issue switching from Axios to Fetch in the expected types being returned. My original code with Axios is as follows:

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"
}

The result of the response is JSON:

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

so I am just destructuring it and returning library in the function, which is a string.

I am trying to switch to fetch now:

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;  
}

and the line const { library } = await response.data; is giving me a TS error of Property 'library' does not exist on type 'unknown'.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

fetch.json() returns a Promise<unknown>, TypeScript doesn't let you grab a property of unknown because it doesn't know if it exists on the response object, hence the error.

Property 'library' does not exist on type 'unknown'.

You could cast your response to what you expect from the request.

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

In your case, you could create an interface for the expected response.

// 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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda