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.