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

192
Views
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 answers
Answer question

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 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!