How can a TypeScript function be used to retrieve a string (or JSON object)?

When attempting to retrieve data from a web API using TypeScript and return the JSON object, encountering an error has left me puzzled. Inside my function, I can successfully display the fetched data on the console, but when I try to return it with return data;, the compiler throws an error claiming that nothing is being returned. Can someone please point out what mistake I am making here?

async function fetchData(url: string, query: string): Promise<string> {

  const axios = require('axios');
  axios.get(url, {params: {"query": query}})
  .then(function (response: any) {
    let data = JSON.stringify(response.data);
    console.log("data: " + data);
    return data;
  })
  .catch(function (error: any) {
    console.log(error);
    return "error";
  });

}

var url: string = 'https://api.example.com/data';
var query = "{exampleData}"
var result = fetchData(url, query).catch(e => console.error(e)).finally(() => process.exit(0))
console.log("result:" + result);

The output message received:

src/index.ts:1:50 - error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value.

1 async function fetchData(url: string, query: string): Promise<string> {

In this scenario, I am aiming to return either a string or a JSON object as part of the solution I seek. The challenge lies in successfully returning either of these data types.

Answer №1

If you're looking for a workaround, one option is to return the promise within your function, define the variable res globally, and then assign the resolved value from the promise callback to res.

Keep in mind that the assignment will only occur once the promise has been fulfilled, so you may need to utilize a timeout if you plan on using the variable outside of the callback.

Here's an example:

function retrieveData(url: string, query: string): Promise<any>{
  const axios = require('axios');
  return axios.get(url, {params: {"query": query}});
}

var url: string = 'https://api.example.com/data';
var query = "{getData {nodes{id name}}}"
var res;

retrieveData(url, query).then(function (response: any) {
  res = JSON.stringify(response.data);
}).catch(function (error: any) {
  res = error;
});
  

setTimeout(() => {console.log("Result:" + res);}, 3000);

Alternatively, a more reliable approach would be to handle everything related to res inside the promise callback itself.

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

Encountering issues with integrating interactjs 1.7.2 into Angular 8 renderings

Currently facing challenges with importing interactive.js 1.7.2 in Angular 8. I attempted the following installation: npm install interactjs@next I tried various ways to import it, but none seemed to work: import * as interact from 'interactjs'; ...

How can I use TypeScript to wrap a component in Vue 3?

Looking to customize a PrimeVue component (Calendar) by styling it differently and then re-exporting it. Here's an example in React: const WrappedCalendar: React.FC<CalendarProps> = (props)=> <div style={{background:'green'}}&g ...

The JSON at position 0 threw a curveball with an unexpected token "u

Whenever I attempt to convert a string to an object, I encounter an error: Unexpected token u in JSON at position 0 Service setUser : function(aUser){ //save User localStorage.setItem('User', JSON.stringify(aUser)); }, getUser ...

Converting Data Types in Typescript

So I'm working with Data retrieved from a C# Rest Server. One of the values in the array is of type Date. When I try to perform calculations on it, like this: let difference = date1.getTime() - date2.getTime(); I encounter the following error messag ...

Eliminating quotation marks within JSONObject operations

Currently, I am utilizing the net.sf.json.JSONObject library to generate data for a front end application. However, it seems that the code I am working with is automatically adding quotation marks to every field name in the output. For instance: myStrin ...

Packaging a NodeJS project in Visual Studio - A step-by-step guide to creating and setting up an N

In my VS2013 solution, I have a combination of NodeJS (using TypeScript) and C# class library projects connected by EdgeJS. Among the NodeJS projects, one serves as a library for a RabbitMQ bus implementation, while two are applications meant to be hosted ...

Exploring Facebook JSON data structures in PHP

Currently working on retrieving the user location data from Facebook. According to the User page on the Graph API, it mentions: location : A JSON object containing name and id I specifically require the location name, but I'm having trouble obtaini ...

Encountering a problem with lazy loading of module routing paths. Issue arises when attempting to navigate to http://localhost:4200

AppLazyLoadingMoudle import {NgModule} from '@angular/core'; import {RouterModule, Routes} from '@angular/router'; const ROUTES : Routes = [ /* ProductModule (defined in the feature module) is loaded lazily when navigating ...

Error Detected: An unhandled error occurred, triggering a promise rejection: TypeError: The super expression must be either null or a function in Angular version 6

Upon deploying the application on AWS Elastic Beanstalk, an error has surfaced. While the build and deployment processes were successful, one module is giving a Super Expression error. The other modules are functioning correctly, and everything works fine ...

Improprove the types generated from GraphQL responses

I am facing a major challenge with the types while using GraphQL. My intention is to send a request and store the result in a React state with a well-defined type. However, I want to avoid declaring it as const [animals, setAnimals] = useState<AnimalsLi ...

How can I retrieve the Google Maps URL containing a 'placeid' using AJAX?

I have a specific URL that I can access through my browser to see JSON data. The URL appears as follows: https://maps.googleapis.com/maps/api/place/details/json?placeid=ChIJZeH1eyl344kRA3v52Jl3kHo&key=API_KEY_HERE However, when I attempt to use jQuer ...

I am attempting to include the headers in my HTTP GET Json request. The API key documentation has provided me with a specific format for the API key that I need to use

This is the original format: response = requests.get(PAPERQUOTES_API_ENDPOINT, headers= {'Authorization': 'TOKEN {}'.format(TOKEN)}) Here is my attempt to replicate it (still unsure about the use of brackets and the function format ...

TypeScript's standard React.Children interface for compound components

One of my components is a Table, which can have children that are Column components: <Table data={data}> <Column cell={(c) => c.date} header="Date" /> <Column cell={(c) => c.count} header="Count" /> & ...

Exploring nested objects within an instance

I'm facing an issue with accessing a variable object within my main object. I am able to access 'start', 'end', and 'category' without any problem, but I am unsure how to access the variable Object in my Angular web app d ...

Angular: Clicking on a component triggers the reinitialization of all instances of that particular component

Imagine a page filled with project cards, each equipped with a favorite button. Clicking the button will mark the project as a favorite and change the icon accordingly. The issue arises when clicking on the favorite button causes all project cards to rese ...

Changing NSString to NSDictionary in Objective-C

This is the unique text { UniqueModel = XYZ; DPIHeight = 144; DPIWidth = 144; Depth = 16; Orientation = 2; PixelHeight = 5696; PixelWidth = 8576; ProfileName = "XYZ Color Profile"; "{Custom}" = ...

Utilizing custom colors in a Typescript/React/MUI Button component to enhance its design

How can I apply custom colors to the Button component without getting an error? Are there any possible solutions for this issue? I followed the module augmentation approach outlined in the documentation, but the problem persists: https://mui.com/material ...

Transform object into JSON format

Is there a way to transform an object into JSON and display it on an HTML page? let userInfo = { firstName: "O", lastName: "K", email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2b44476b445b05484446">[ema ...

Angular - The argument provided is not compatible with the parameter

I encountered the following TypeScript errors in app.component.ts: Issue: Argument of type '(events: Event[]) => void' is not assignable to parameter of type '(value: Event[]) => void'. Description: Types of parameters 'events& ...

Deciphering a JSON array in PHP

After retrieving a decoded JSON array from the Facebook API, here is how it looks when printed: $Myposts = json_decode($response->getBody()); var_dump($Myposts); It displays various messages with their corresponding created times and IDs. Now, I want ...