'Typescript: consider a generic type as Array

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



Solution 1:[1]

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);
}

TypeScript Playground Link

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 sno2