typescript in conjunction with nested destructuring

ES6 has definitely made coding more efficient by reducing the number of lines, but relying solely on typescript for everything may not be the best approach.

If I were to implement type checking for arguments that have been destructed multiple levels deep, wouldn't it become a bit messy? Perhaps using interfaces for initial checking would suffice, rather than typechecking every single thing. It's important to strike a balance and avoid overusing ES6 for the sake of readability. What are your thoughts on this?

<div>
      {response.results.map(({id, name, stock: {day: dayStock, month: monthStock}}) => {
        return(
          <div>
            <p>Item: {name}</p>
            <p>Day Stock: {dayStock}</p>
            <p>Month Stock: {monthStock}</p>
            <br />
          </div>
        )
      })}
    </div>

Check out the typescript playground here: https://codesandbox.io/s/v06ml2y130

Answer №1

It is possible to add annotations to the destructured object if you log in your findings.

type Discovery = {
    number: number;
    title: string;
    origin: {
        country: string;
        city: string;
        date: string;
    };
}

const output = {
    findings: [{
        number: 1,
        title: 'Artifact',
        origin: {
            country: 'Greece',
            city: 'Athens',
            date: '500 BC'
        }
    }]
};

output.findings.map(
    ({ number, title, origin: { city: discoveryCity } }: Discovery) => discoveryCity
);

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

What methods can be utilized to ensure that my wistia video player/playlist is responsive on different devices

I need some assistance with making my Wistia player responsive while using a playlist. I want the video player to adjust its size based on the screen size. Here is an example: My current code utilizes their iframe implementation: <div id="wistia_1n649 ...

Extension for Firefox: Unable to access variables or functions from the movie_player element on YTMusic

Looking to develop a Firefox extension for hosting "Yt-Music parties" where users can sync up with the host YtMusic. The "movie_player" element houses various functions and variables that could be valuable, such as the current song time. Strange enough, ...

What is the best method for fetching the values of a select element in React.js?

I'm struggling to retrieve the value of a selected element in a dropdown list. I've tried debugging it, but haven't been able to get the value. I attempted to console log e.target.value, but unfortunately, it didn't work. Any thoughts o ...

When adding new elements to an array, the IDs of all objects become identical

When running the code below: dietDay.meals.forEach((meal) => { meal.mealProducts.forEach((mealProduct) => { if ( mealProduct.product.id && this.fetchedProductIds.includes(mealProduct.p ...

Utilize $.ajax to gracefully wait for completion without causing the UI to freeze

Consider a scenario where there is a JavaScript function that returns a boolean value: function UpdateUserInSession(target, user) { var data = { "jsonUser": JSON.stringify(user) }; $.ajax({ type: "POST", url: target, data: ...

How can Angular hide a global component when a particular route is accessed?

Is it possible to hide a global component in Angular when a specific route is opened? For instance, consider the following code: app.component.html <app-header></app-header> <app-banner></app-banner> <!-- Global Component I w ...

Bug in Chrome causing issues with autofilling fields in AngularJS applications

Seeking a solution to address a bug noticed while utilizing a custom Angular directive in conjunction with Chrome's autofill feature. The directive is designed for a phone number field, automatically adding dashes "-" to enhance user experience by eli ...

Retrieve information using the useEffect hook on a server-side rendered webpage

I am currently working on a project using React JS and Next JS. The page is dynamic, utilizing getStaticPaths and getStaticProps to fetch most data on the server side for rendering. However, there are certain pieces of data that require a token stored in l ...

In Typescript, we can use a class to encapsulate another class and then return a generic result

Trying to wrap my head around the concept of generic classes, and now I need to dynamically create another class. However, I am uncertain about how to go about it. Class A {} Class B<T> { Return T } Const c = B(A); // which is T More context on w ...

Stop the click event from firing on child elements of a parent element that is currently being dragged

Below is the structure of a UL tag in my code: <ul ondrop="drop(event)" ondragover="allowDrop(event)"> <li class="item" draggable="true" ondragstart="dragStart(event)" ondrag="dragging(event)"> <div class="product-infos"> ...

Have you ever wondered why req.body returns as undefined when using body parser?

Every time I attempt to make a post request, I keep receiving an error message stating that req.body is returning as undefined. Below is the content of my server.js file: import express from 'express'; import bodyParser from 'body-parser&ap ...

Interactive Bar chart updates in real-time with Highcharts and AngularJs

With the help of a sample from Highcharts (here), I successfully integrated a bar chart into AngularJs. Below is the HTML code: <!DOCTYPE html> <html ng-lang="en" ng-app="myModule"> <head> <meta charset="ISO-8859-1"> <script sr ...

I'm having some trouble with this search filter in Vue 2 - is it failing to display the items as expected

After struggling with this issue for over a week, I've hit a roadblock and need some assistance. I'm currently working on implementing a search filter in Vue 2 with Vuetify, but something isn't quite right. Here's a snippet of the sea ...

Steps to transfer the content of a label when the onclick event occurs

Seeking advice on how to send the dynamically varying value of a label upon clicking an anchor tag. Can anyone recommend the best approach to passing the label value to a JavaScript function when the anchor is clicked? Here is a sample code snippet: < ...

Using a jQuery gallery can cause links to become unresponsive and unclickable

While creating a responsive webpage with the Zurb Foundation framework, I encountered an issue when trying to incorporate nanoGallery which also uses jQuery. After adding the gallery scripts, the top menu generated by the Foundation script became unclickab ...

The JSON property is not defined

After making an AJAX call to retrieve data, I receive a JSON Object instead of a string. When I log the object, all its properties appear correctly. However, when attempting to log one specific property, it shows up as undefined. Here is a snapshot of my ...

Tips for updating and triggering useEffect when the router changes in React JS

I have a ChartPage function that is being called three times within three different routers. Inside the ChartPage function, I am using "useEffect" to update some variables based on the selected route. However, for some reason, it only triggers once, and wh ...

Is it necessary to have n_ if I've already set up lodash?

After some research, I came across a recommendation to install lodash. However, upon visiting the lodash website, they suggest that for NodeJS, n_ should be installed instead. Are both necessary? Is one more comprehensive than the other? Do I even need eit ...

I'm looking to locate the API documentation for AngularJS TypeScript

After transitioning from using AngularJS 1.4 and plain JavaScript to now working with AngularJS 1.5 but utilizing TypeScript, I have found it challenging to find helpful documentation. For instance, when trying to inject services like $q or $timeout into m ...

What is the best way to implement custom sorting for API response data in a mat-table?

I have been experimenting with implementing custom sorting in a mat-table using API response data. Unfortunately, I have not been able to achieve the desired result. Take a look at my Stackblitz Demo https://i.sstatic.net/UzK3p.png I attempted to implem ...