The 'data' property is absent in the 'never[]' type, whereas it is necessary in the type of product data

Hello, I am new to TypeScript and I'm struggling with fixing this error message:

Property 'data' is missing in type 'never[]' but required in type '{ data: { products: []; }; }'.

Here is my code snippet:

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 = [];
}

Answer №1

There are a couple of issues that need to be addressed:

  1. 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.
  2. 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.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with debugging Azure Functions TypeScript using f5 functionality is unresolved

I am encountering issues running my Azure TypeScript function locally in VS code. I am receiving the errors shown in the following image. Can someone please assist me with this? https://i.stack.imgur.com/s3xxG.png ...

Ways to broaden React categories for embracing html attributes as props?

When designing a component that accepts both custom props and HTML attribute props, what is the best approach for creating the interface? The ideal interface should also accommodate React-specific HTML props, such as using className instead of class. Here ...

Set up a unique database in memory for every individual test

Is it feasible to create an in-memory database for each test scenario? My current approach involves using the code snippet below, which functions properly when running one test file or utilizing the --run-in-band option. import _useDb from "@/useDb&q ...

Retrieve information for the designated page exclusively

When retrieving data from the backend using a service, I encounter an issue where the system may slow down if 2000 records are returned in one request. To address this, I would like to display only 10 records per page and fetch the next 10 records with eac ...

Using Firebase with Angular 4 to fetch data from the database and show it in the browser

Currently diving into Angular 4 and utilizing Firebase database, but feeling a bit lost on how to showcase objects on my application's browser. I'm looking to extract user data and present it beautifully for the end-user. import { Component, OnI ...

D3-cloud creates a beautiful mesh of overlapping words

I am encountering an issue while trying to create a keyword cloud using d3 and d3-cloud. The problem I am facing is that the words in the cloud are overlapping, and I cannot figure out the exact reason behind it. I suspect it might be related to the fontSi ...

What is the recommended TypeScript type for setting React children?

My current layout is as follows: export default function Layout(children:any) { return ( <div className={`${styles.FixedBody} bg-gray-200`}> <main className={styles.FixedMain}> <LoginButton /> { children } ...

What is the procedure for accessing a namespace when declaring it globally?

Website Project Background Currently, I am working on a simple website where users can update their pictures. To achieve this functionality, I am utilizing the Multer library along with Express in Typescript. Encountered Issue I am facing a challenge re ...

Tips for importing a .geojson document in TypeScript using webpack?

I am trying to extract data from a .geojson file but faced some challenges while attempting two different methods: const geojson = require('../../assets/mygeojson.geojson'); The first method resulted in an error message stating: Module parse f ...

Definition of a Typescript Global.d.ts module for a function that is nested within another function

Simply put, I have a npm module that exports a function along with another function attached to it: // @mycompany/module ... const someTool = (options) => { // do some cool stuff }; someTool.canUseFeature1 = () => { return canUseSomeFeature1(); ...

The Aurelia application encounters a "Maximum call stack size exceeded" error while trying to bind FullCalendar

I am currently working on setting up a JQuery plugin (FullCalendar) within my Aurelia application, which is built using TypeScript. I am relatively new to web development and just trying to get a basic example up and running. To start off, I utilized this ...

Exploring Nested <Routes> with ReactJs

My decision on whether to display the Foo page or the Bar page is based on the route. However, the Foo page itself contains two sub-routes for components to render depending on the URL path - such as FooOne or FooTwo. This results in having two layers of r ...

I am having trouble getting my custom colors to work with hover effects in Tailwind CSS

The code I have written is for a header component in Next.js with Typescript and Tailwind. I named it Header_2 to represent a component display in a library. Initially, the custom colors were not rendering as expected, but I managed to resolve the issue by ...

Searching for particular information within an array of objects

Seeking guidance as a newbie on how to extract a specific object from an array. Here is an example of the Array I am dealing with: data { "orderid": 5, "orderdate": "testurl.com", "username": "chris", "email": "", "userinfo": [ ...

Exploring the power of utilizing multiple classes with conditions in Angular 2+

Can you help me figure out how to use a condition for selecting multiple classes with [ngClass] in Angular? <td> <span [ngClass]="{ 'badge badge-success': server.type === 'PRODUCTION', 'ba ...

How to make an optional prop with a default value non-nullable in a ts+react component?

Is there a way to modify a React component to accept an optional prop and then treat it as non-null within the component itself? For example, consider the following basic component: import React from 'react'; type props = { x?: number; }; c ...

Angular 2 event emitter falling behind schedule

I am currently utilizing Angular 2 beta 6. The custom event I created is not being captured import {Component, OnInit, EventEmitter} from 'angular2/core'; import {NgForm} from 'angular2/common'; import {Output} from "angular2/core" ...

Typescript throws an error when attempting to return an array of strings or undefined from a function

I created a shallow differences function that compares two arrays of strings and returns either undefined (if the arrays are different lengths) or a string array containing matching characters at corresponding indexes. If the characters don't match, i ...

Custom Angular 2 decorator designed for post-RC4 versions triggers the 'Multiple Components' exception

Currently, I am in the process of updating my Ionic 2 component known as ionic2-autocomplete. This component was initially created for RC.4 and earlier iterations, and now I am working on migrating it to Angular 2 final. One key aspect of the original des ...

What causes parameters to be undefined when making a DELETE request in my Next.js application running on version 14.1.4?

I am encountering an issue with my DELETE mapping export async function DELETE({params} : {params: {id: string}}) { try { const loanToDelete = await prisma.loan.findUnique({ where: { id: parseInt(params.id) } }) if (!loanToDelete ...