I'm running parallel requests for a series of fetches. I want to type results
as an array of response objects (instead of array of type any
) but I'm unsure of how to do this. I googled "how to type response object in Typescript" but didn't get useful hits. Is there a way to type the response object other than manually creating a custom type that has all the properties on a response object? Does Typescript have a special built in type we could use here?
const results: any = []; fetch(URL, { headers: { ... } }) .then(response => { results.push(response); }) .catch(err => { ... }) const responses = await Promise.all(results); return responses;
Since I am using node-fetch
, I ended up with the following solution. https://www.npmjs.com/package/node-fetch#class-response
import { Response } from 'node-fetch';
const results: Response[] = [];
fetch(URL, {
headers: {
...
}
})
.then(response => {
results.push(response);
})
.catch(err => {
...
})
const responses = await Promise.all(results);
return responses;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.