Home > Blockchain >  How to correctly use generics in typescript?
How to correctly use generics in typescript?

Time:11-09

I get stuck with generics . How can I correctly use generics in my case:

export interface Location {
  id: number;
  address: {
    houseNumber: string;
  };
}
export const getEuropeLocations = async (
  apiKey: string
) => {
  let response = await axios.get<Location>({ 
    method: "get",
    url: `${apiBaseUrl}europe/`,
    headers: {
      Authorization: `Bearer ${apiKey}`,
    },
  });
  return response.data;
};

have error with types : "{ "message": "Argument of type '{ method: string; url: string; headers: { Authorization: string; }; }' is not assignable to parameter of type 'string'.",

}"

CodePudding user response:

Axios has typings for this. It lets you specify a generic type for the axios functions so that result.data will have that generic type.

For example, you can do this:

import axios from "axios";

export const getEuropeLocations = async (
  apiKey: string
) => {
  let response = await axios.get<Location>({
    method: "get",
    url: `${apiBaseUrl}europe/`,
    headers: {
      Authorization: `Bearer ${apiKey}`,
    },
  });
  return response.data;
};

If you want to make the entire function generic, you can do this:

export const getEuropeLocations = async <T>(
  apiKey: string
) => {
  let response = await axios.get<T>({
    method: "get",
    url: `${apiBaseUrl}europe/`,
    headers: {
      Authorization: `Bearer ${apiKey}`,
    },
  });
  return response.data;
};
  • Related