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

Dealing with errors from APIs in a React TypeScript application

Currently, I am in the process of learning React and Typescript by creating a demo application. This app sends a request to the API located at in order to retrieve postcode information and display details about a specific location based on the entered pos ...

How to Serialize a Dictionary in C# Without Using the "key" and "value" Keywords

I am having difficulty serializing the data structure shown below into JSON: public class TestClass { public TestClass() { Translations = new List<Dictionary<string, Dictionary<string, string>>>(); } [JsonProp ...

The request body doesn't meet the interface requirements, but it does not trigger an error response

I created a specific interface called NewTransactionPayload to ensure that only objects of this type are accepted in the request body. Strangely, TypeScript does not show any errors when I host the application. Why is that? // Sample interfaces interface ...

Converting a structure into JSON in the Go programming language

I am struggling with encoding a struct to JSON in my code. Here is what I have: json:"text,omitempty" Array []TestArray json:"test_array,omitmepty" } type TestArray struct { ArrayText string json:"array_text,omitempty" } func main() { Test : ...

Deep Dive into TypeScript String Literal Types

Trying to find a solution for implementing TSDocs with a string literal type declaration in TypeScript. For instance: type InputType = /** Comment should also appear for num1 */ 'num1' | /** Would like the TSDoc to be visible for num2 as well ...

Struggling to make HttpClient Post work in Angular 5?

I'm facing an issue with my httpClient post request. The service is not throwing any errors, but it's also not successfully posting the data to the database. Below is the code snippet: dataService.ts import { Injectable } from '@angular/c ...

Obtain the JSON response from the servlet

Is there a way to get a JSON response from a servlet in JavaScript? I am using AJAX post to send data to the servlet. Here is my AJAX code $.ajax({ type: "POST", url: "formDelegationServlet", data: { ...

"Executing the jar file results in 'JAX-RS MessageBodyWriter not found for media type=application/json' error, however running mvn:exec works perfectly

I am facing a challenge while trying to package my maven project. Initially, I developed and tested it using mvn:exec and everything worked perfectly fine. However, after generating the jar file with dependencies using mvn package, I encountered an issue. ...

Error in Typescript: 2 arguments were provided instead of the expected 0-1 argument

When attempting to run a mongoose schema with a timestamp, I encountered an error: error TS2554: Expected 0-1 arguments, but got 2. { timestamps: true } Below is the schema code: const Schema = mongoose.Schema; const loginUserSchema = new Schema( { ...

Ignoring empty lists in Jackson - A simple guide

My web service needs to pass these entities as JSON objects: @Entity(name = "exams") public class Exam { @Id @GeneratedValue private int id; @Column(name = "exam_name") private String name; @JoinColumn(name = "exam_id") @One ...

What is the method to retrieve the unique individual IDs and count the number of passes and fails from an array

Given a data array with IDs and Pass/Fail statuses, I am looking to create a new array in Angular 6 that displays the unique IDs along with the count of individual Pass/Fail occurrences. [ {"id":"2","status":"Passed"}, {"id":"5","status":"Passed"}, {"id": ...

Tips for transforming an array of images (from an input field) into a JSON string

After creating an array of images using var a = Array.from(document.getElementById("id").files); I tried to generate a JSON string of that array using var b = JSON.stringify(a); However, all I get is an empty array. It seems like this issue is common w ...

What is the best way to transform a JSON string into a set of key-value pairs?

I am looking to extract all the key-value pairs nested under the "tags" section within "instanceData" and reformat them as direct key-value pairs under "properties". The initial data looks like this... { "id": "/subscriptions/1234abcd-ab12-12ab-12ab-ab ...

In React Router v6, you can now include a custom parameter in createBrowserRouter

Hey there! I'm currently diving into react router v6 and struggling to add custom params in the route object. Unfortunately, I haven't been able to find any examples of how to do it. const AdminRoutes: FunctionComponent = () => { const ...

Processing JSON in a List

My struggle lies in processing a Scala list effectively: At present, I have a list that resembles the following (List(JString(2437), JString(2445), JString(2428), JString(321)), CompactBuffer((4,1))) After processing, my desired outcome is as follows: ...

Transferring 'properties' to child components and selectively displaying them based on conditions

This is the code for my loginButton, which acts as a wrapper for the Button component in another file. 'use client'; import { useRouter } from 'next/navigation'; import { useTransition } from 'react'; interface LoginButtonPr ...

Typescript is throwing an error stating that utilizing 'undefined' as an index type is invalid

When working with TypeScript and React, I pass xs, sm, md, lg as props to the component. Each size corresponds to a specific pixel value (14px, 16px, 18px, 24px) that is then passed to an Icon component. The errors mentioned in point (1) occur at the line ...

Guide to exporting (and using) JSDoc annotations in TypeScript NPM packages

Looking to enhance my skills in creating npm packages with TypeScript. I have a small project available at https://www.npmjs.com/package/lynda-copy-course/, and so far, the project structure is successful in: being executable from the command line after ...

Error message from OpenAI GPT-3 API: "openai.completions function not found"

I encountered an issue while trying to execute the test code from a tutorial on building a chat app with GPT-3, ReactJS, and Next.js. The error message I received was: TypeError: openai.completions is not a function This occurred when running the follow ...

Generating TypeScript Type Definitions for dynamic usage

In my client server application, I use REST calls for communication. To avoid using the wrong types by mistake, I have defined all RestCalls in a common file (excerpt): type def<TConnection extends Connections> = // Authentication ...