There are a couple of issues that need to be addressed:
- The problem arises from TypeScript inferring the type of
res
and using an empty array []
for products
. This leads TypeScript to infer never[]
because it doesn't have information about the elements in the array, affecting both res
's products
and medias
.
- Although you've specified that the type of
res
should be an object with a data
property, initializing it with just []
contradicts this specification.
To resolve these issues, avoid inferring types and explicitly declare the expected type for the arrays. You can also utilize a generic type argument with axios.get
to specify the expected type for the data
returned by the request. For example, if you anticipate an array of strings:
let medias: string[] = [];
// ^^^^^^
try {
const res = await axios.get<{ products: string[] }>(
// ^^^^^^^^^^^^^^^^^^^^^^^^
"https://dummyjson.com/products?limit=10&skip=10"
);
medias = res.data.products;
} catch (e) {
// No need to reassign `medias` to an empty array here since it's done earlier
}
If you're expecting an array of a different type, simply replace string
with the appropriate type above.