I encounter this case in my recent work, and I can't figure a good solution. I hope some one can provide me tips with this;)
I generated my types from a swagger to typescript parser.
It gave me types for all routes, looking like
type GetXXXCollection = {
responseBody: XXXType[]
}
A linked that with axios to fetch
const fetchXXX = () => axios.get<GetXXXCollection.responseBody>(uri)
and it works just fine.
I'm trying to build a generic fetch to parse my data with something like
const fetchXXXParsed = (uri) => genericFetchThenParse<GetXXXCollection.responseBody>(uri)
const genericFetchThenParse = async <T>(uri) => {
const res = await axios.get<T>(uri)
// I want to map over my results
res.data.map(...)
}
Is there a way to make genericFetch
T type act like an array
You need to strengthen the constraints of T
to be an array. This can be done by making sure it extends unknown[]
:
import axios from "axios";
declare namespace GetXXXCollection {
export type responseBody = { foo: number }[];
}
const fetchXXXParsed = (uri: string) => genericFetchThenParse<GetXXXCollection.responseBody>(uri)
const genericFetchThenParse = async <T extends unknown[],>(uri: string) => {
const res = await axios.get<T>(uri)
res.data.map(data => data);
}
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.