Hi i am new in typescript please how can fix this error that says
Property 'data' is missing in type 'never[]' but required in type '{ data: { products: []; }; }'.
here is by code:
let medias :[] = [];
let res :{
data: {
products: []
},
} =[];
try {
res = await axios.get('https://dummyjson.com/products?limit=10&skip=10');
medias = res.data.products;
} catch (e) {
medias = [];
}
There are at least two problems:
res
, but using just []
as products
. Since TypeScript doesn't know what the elements will be, it infers never[]
. This issue applies both to res
's products
and to medias
.res
is an object with a data
property, but then you're trying to initialize it with just []
.Instead, use non-inferred types, and say expressly what type you expect in the array. You can also use a generic type argument with axios.get
(because it's a generic method) to say what you expect the data
to be. For instance, if you're expecting 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 for `medias = []` here, you've already done it above
}
If you're expecting an array of something else, just use that instead of string
above.