I'm trying to render an API response on a React + TypeScript view component. Here are the interfaces that are used to represent the API response (in this case stocks) and API error:
export interface IStocks {
[key: string]: string;
}
export interface IErrors {
[key: string]: string;
}
Here is a function that gets the stocks from some API, there are compile time errors which I need help for:
private async getStocks(): Promise<IStocks> {
/*
Generic type 'Promise<T>' requires 1 type argument(s).ts(2314)
Ok, but how do I make this function know about IErrors and IStocks types? What is the correct way?
*/
try {
let response = await fetch('http://localhost:8080/api/v1/stocks', {
method: "get",
headers: new Headers({
"Content-Type": "application/json",
Accept: "application/json"
})
});
return (IStocks) response;
/*
'IStocks' only refers to a type, but is being used as a value here.ts(2693)
I wanted to map the response to 'IStocks' interface simply, my way is incorrect but then how do I do it
*/
} catch (ex) {
return (IErrors) ex;
/*
'IErrors' only refers to a type, but is being used as a value here.ts(2693)
I wanted to map the response to 'IErrors' interface simply, my way is incorrect but then how do I do it
*/
}
return null;
}
Basically, I want to map the API error object ex to the IErrors interface for type checking and the API response object to the IStocks interface.
What is the correct way to do it?