Using TypeScript, the fetch function cannot be assigned

Why am I encountering this TS warning?

Type 'unknown' is not assignable to type 'PokemonList'.ts(2322)

This issue is on line: "return e"

Here is the code snippet:


export interface PokemonList {
  count: number;
  next: string;
  previous?: any;
  results: {
    name: string;
    url: string;
  }[]
};


const PokeApi = async (): Promise<PokemonList> => {
  try {
    const res = await fetch('https://pokeapi.co/api/v2/pokemon?limit=10');
    return res.json()
  } catch(e) {
    return e;
  }
};

After making this change:

( Promise<PokemonList> | unknown )

I receive this new error message:

The return type of an async function or method must be the global Promise<T> type. Did you mean to write 'Promise<unknown>'?ts(

Answer №1

The output type of that function is

Promise<PokemonList | Error>

Keith pointed out that this approach is not ideal as it breaks the promise chain. Promises are designed to be chained using .catch and try/catch, but your implementation requires an if/else statement, which goes against the principles of Promises.

To resolve this issue, you should eliminate the try/catch block within the function and handle errors with catch when calling it.

const PokeApi = async (): Promise<PokemonList> => {
  const res = await fetch('https://pokeapi.co/api/v2/pokemon?limit=10');
  return res.json()
};

// example of calling the function inside an async function

let pokemonList: PokemonList;
try {
  pokemonList = await PokeApi();
} catch (e) {
  // Handle error
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

React Dependency Error

Allow me to outline my current situation: I integrated the react-native-multiple-select-list package into my react-native project by executing: 'yarn add react-native-multiple-select-list': "dependencies": { "react-native-multiple-select ...

Is your HighCharts navigator and range scale malfunctioning?

Looking for assistance on limiting min and max values from a JSON array using JavaScript. I am facing an issue while working with Highstocks. The date is the first day in Unix, but the array contains the correct date. As a result, my navigator and range s ...

The order of key:value pairs in documents created by Mongoose does not always align with the schema

Having trouble understanding how the Mongo .create and .findAndUpdate operations work. My mongoose version is 5.4.2X and I have a model with a schema containing multiple key:value pairs in a specific order (using 1. 2. 3. etc to indicate the correct order) ...

Is it possible to limit the items in a TypeScript array to only accept shared IDs with items in another array?

I'm creating an object called ColumnAndColumnSettings with an index signature. The goal is to limit the values of columnSettings so that they only allow objects with IDs that are found in columns. type Column = { colId: string, width?: number, s ...

Issue with Masonry.js implementation causing layout to not display correctly

Currently, I am working on a project using Laravel, VueJS, and the Masonry.js library to develop a dynamic gallery. However, I have encountered a peculiar issue. Here is a snippet of my VueJS template: <template lang="html"> <div id="uploads-g ...

Using Props to Render Polylines on Google Maps Display

Below is the ReactJS code snippet to showcase a vehicle's movement on Google Maps. Within the code, latitude and longitude coordinates are hardcoded in the path array. I am looking for guidance on how to pass latitude and longitude coordinates to the ...

Setting up the propTypes for interface in React TypeScript

How can I specify the correct PropTypes for a property that is an interface in TypeScript with PropTypes? Requirements - Implementing both TS and PropTypes. Goal - To have a more precise type definition than PropTypes.any that meets standard eslint an ...

React - Ensure useEffect is triggered only after state update

One of my components (ItemsIndex) is using a custom hook to fetch data from our API. However, the ItemsIndex's useEffect runs first, causing the DOM to not be filled with elements that could be scrolled into view. How can I make sure that the useItems ...

leveraging a Nuxt plugin and saving it in middleware

My goal is to create a middleware that validates the authentication and entitlement of users. The authentication details are retrieved from my store: //store/index.js const state = () => ({ auth: { isLoggedIn: false // more properties here } ...

Angular 17: Issue with _HttpClient Provider Not Found in Standalone Component Utilizing ApiService

I have been developing a cutting-edge Angular 17 application that integrates the Spotify API using the innovative standalone component functionality. However, I am facing an issue while attempting to inject the HttpClient into a service. Despite meticulous ...

The successful loading of tab favicons in the DOM of an angular chrome extension is a triumph, however, explicit XHR requests are unfortunately

I've been immersed in developing a Chrome extension with Angular 5. Successfully, I managed to extract favIconUrls from the tabs API and link them to my popup.html's DOM. The icons are retrieved and displayed without any hiccups. See an example ...

Can you explain the distinction between using "require" to return a module and accessing the actual object in node.js?

When working with node.js, the commonly used method to include modules from other files is by using "require", whether it's from our own code or third-party libraries. But for me, there seems to be some confusion regarding the distinction between the ...

Ways to access the scrollTop attribute during active user scrolling

I've been working on a website that utilizes AJAX to keep a chat section updated in real-time. One issue I encountered was ensuring the chat automatically scrolled to the bottom when a user sent a message, but remained scrollable while new messages we ...

Tips for avoiding duplicate elements in ASP.NET during postback

My issue is that I have a div with the ID "mydiv" and runat=server. <div ID="mydiv" runat="server"></div> I move mydiv to a Container using jQuery. $("#mydiv").appendTo('#Container'); After a PostBack, my div gets duplicated and I ...

Customizing the default settings of a d3 funnel chart

I recently used the following link to create a funnel chart using D3: jakezatecky/d3-funnel Everything was working perfectly. However, I wanted to adjust the block heights in proportion to their weight as mentioned in the tutorial by changing the D3 defau ...

Numerical values are not considered by the JavaScript table filter

I'm having trouble with dynamically filtering the content. It works fine for the first two columns, but not for the third one. Maybe I need some additional JavaScript? Here is the link to my snippet: `https://www.w3schools.com/code/tryit.asp?filen ...

How to display an array with JSON objects in Angular 4

Looking to display specific data from an array in my .html file that originates from my .ts file: myArray: ["03/05/2018", "2:54", "xoxo", "briefing", "your", [{ "Id": "1", "Time": "20:54", "Topic": "mmmmm", "GUEST1": { "Role": "HS" ...

Is it advantageous to combine socket.io with express for seamless communication in web applications? If the answer is yes, what is the best approach to integrating

Embarking on my journey into back-end development, I am currently delving into the task of creating a simulated money poker website. Leveraging Node.js along with socket.io, express-session, and passport, I initially relied heavily on express with an HTTP ...

Implementing a rate limit on the login API that is specific to individual IP addresses rather than being

I have successfully implemented the [email protected] module, but I am facing an issue where it is blocking the API globally instead of for a specific API that is receiving hits. This is my current code: const limiter = new RateLimit({ windo ...

Learn how to easily copy the success result from an Ajax call to your clipboard

Is there a way to use an ajax method to retrieve data from a controller and display it in a JQuery Dialog Box? I want to add a button within the dialog box that allows the user to easily copy the data with a single click, instead of having to manually high ...