Issue
I am having an issue switching from Axios to Fetch in the expected types being returned. My original code with Axios is as follows:
private async getAccessType(): Promise<string> {
const config: RequestInit = {
method: "get",
baseURL: SERVER_INFO.URL,
url: '/getData',
headers: {
Authorization: this.token,
"X-Api-key": SERVER.KEY
}
};
const response = await axios(config);
const { library } = await response.data;
return library; // result is "access" or "no-access"
}
The result of the response is JSON:
{
"library": "access",
"name": {
"first": "James"
}
}
so I am just destructuring it and returning library in the function, which is a string.
I am trying to switch to fetch now:
import fetch, { RequestInit } from "node-fetch";
private async getAccessType(): Promise<string> {
const baseURL: SERVER_INFO.URL;
const config: RequestInit = {
method: "get",
headers: {
Authorization: this.token,
"X-Api-key": SERVER.KEY
}
};
const response = await fetch(`${baseURL}/getData`,config);
const { library } = await response.json();
return library;
}
and the line const { library } = await response.data; is giving me a TS error of
Property 'library' does not exist on type 'unknown'.
Solution
fetch.json() returns a Promise<unknown>, TypeScript doesn't let you grab a property of unknown because it doesn't know if it exists on the response object, hence the error.
Property 'library' does not exist on type 'unknown'.
You could cast your response to what you expect from the request.
const { library } = await data.json() as { library: string };
In your case, you could create an interface for the expected response.
// expected response
interface IFetchRes {
library: string;
name: {
first: string;
}
}
// unknown => interpret as expected response
const { library, name } = await data.json() as IFetchRes;
Answered By - axtck
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.