Comparison between Destructuring in TypeScript and JavaScript

Starting my journey with TypeScript after a background in JavaScript.

In the realm of modern JavaScript, one can easily destructure objects like this:

 let {n,s} = {n:42, s:'test'};
 console.log(n, s); // 42 test

Assuming TypeScript follows suit, I tried to apply the same concept. According to the documentation, both declarations and assignments support destructuring. However, my attempt to mimic the JavaScript syntax failed as shown in this sample code:

let {n:number, s:string} = {n:42, s:'test'}; // All destructured elements are unused.
console.log(n, s); // Cannot find name 'n' (nor 's')

What am I overlooking here?

Answer №1

The syntax used above may not be valid. Upon testing it on the TypeScript playground, you'll see that it is invalid. In TypeScript, destructuring behaves just like JavaScript.

It's advisable to define proper typings (such as an interface) for your object before using destructuring.

interface Item {
  n: number;
  s: string;
}

const item: Item = {
  n: 42, 
  s: 'test',
}

let { n, s } = item;
console.log(n, s);

The types of the destructured elements will be automatically inferred from the original object.

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

Properly passing props to child components in React with TypeScript. Resolve Error ts(2322)

I am facing an issue where my code works perfectly in Javascript, but encounters problems when converted to Typescript. Despite the complexity of the question, it actually boils down to a simple query. I just wanted to share the functional JS code as a sol ...

What is the proper way to specify the interface as Dispatch<Action>?

My goal is to create an interface with the dispatch function without using Redux. interface DispatchProps { dispatch: (action: { type: string }) => void; } export function addTwoToNumber({ dispatch }: DispatchProps) { dispatch({ type: '@addTwo ...

I am having trouble with the Primeng password template suggestions not appearing as expected

The demonstration available at this link is not functioning correctly, unlike the example provided in the documentation at this website. In the StackBlitz demo, the suggestions are not being displayed as expected for the password template. Take a look at ...

What is the best way to retrieve the value of an input field in React when incorporating Material UI components?

I am working with a few radio input components that have been imported from material Ui react. Each radio input is wrapped in a FormControlLabel component. <FormControlLabel onClick={checkAnswerHandler} value={answer} control={<Radio color=&quo ...

Encountering difficulty when determining the total cost in the shopping cart

I am currently working on a basic shopping cart application and I am facing an issue when users add multiple quantities of the same product. The total is not being calculated correctly. Here is my current logic: Data structure for Products, product = { ...

Can sweetalert2 be used as a tooltip?

I have a query, is it feasible to include a tooltip in the alert message? Alternatively, could there be another tooltip option available? Swal.fire({ title: '<strong>An example with HTML tags</strong>', icon: 'info', ...

Is there a way to include values in the body of an HTTP GET request using Angular?

I've created a function in my service that looks like this: /** * Retrieve all data * @param sendSelectedValues string */ getAllActPlanBalanceYearData(sendSelectedValues: any): Observable<any> { const url = `/yearlyvalues/act-and ...

Experiencing difficulty creating query files for the apollo-graphql client

I'm currently attempting to learn from the Apollo GraphQL tutorial but I've hit a roadblock while trying to set up the Apollo Client. Upon executing npm run codegen, which resolves to apollo client:codegen --target typescript --watch, I encounter ...

The process of incorporating types into Node.js and TypeScript for handling req and res objects

Check out the repository for my project at https://github.com/Shahidkhan0786/kharidLoapp Within the project, the @types folder contains a file named (express.d.ts) where I have added some types in response. The (express.d.ts) file within the @types folde ...

Struggling to integrate a JavaScript sdk with an Angular2 application due to missing dependencies

I've been struggling to incorporate the Magic: The Gathering SDK library into my Angular2 application. I've tried various methods, but nothing seems to work seamlessly. When I attempt to import the library using TypeScript like this: import { } ...

Transferring data to a different module

I'm currently working on an Angular program where I am taking a user's input of a zip code and sending it to a function that then calls an API to convert it into latitude and longitude coordinates. Here is a snippet of the code: home.component.h ...

Building an Angular 4 app featuring a customized default landing page and URL parameters functionality

I am in the process of developing a web portal that will be embedded within an iFrame. Below is the code snippet I am using to set up the portal: Routes Configuration const routes: Routes = [ { path: '', redirectTo: '/dash ...

Integrating HTTP JSON responses into HTML using Ionic 2, Angular 2, TypeScript, and PHP: A comprehensive guide

Currently in the midst of developing my first Ionic 2 app, however, my understanding of typescript is still limited.. I aim to execute the authenticate() method within my constructor and then to: Retrieve the entire JSON response into the textarea and/o ...

The component 'ProtectRoute' cannot be utilized within JSX

While using typescript with nextjs, I encountered an issue as illustrated in the image. When I try to use a component as a JSX element, typescript displays the message: ProtectRoute' cannot be used as a JSX component. import { PropsWithChildren } from ...

There is an issue with the hook call while trying to establish a context with a reducer

I am facing an issue while setting up the AppProvider component that utilizes a context and reducer to manage global data for my application. The problem seems to be arising from the useReducer hook used within the AppProvider. I have checked the error mes ...

Ways to implement logging in an NPM package without the need for a specific logging library

Currently, I am in the process of developing a company npm package using TypeScript and transferring existing code to it. Within the existing code, there are instances of console.log, console.warn, and console.error statements, as shown below: try { c ...

I am experiencing difficulties with implementing Angular material components in my project

I recently encountered an issue while trying to integrate angular material into my project. Despite importing the MatFormFieldModule, I received the following error: ERROR in src/app/login/components/login/login.component.html:2:1 - error NG8001: &apo ...

TypeError thrown by Mapbox markers

Looking to incorporate markers into my map using Mapbox. Below is the Angular TypeScript code I am working with: export class MappViewComponent implements OnInit { map: mapboxgl.Map; lat = 41.1293; lng = -8.4464; style = "mapbox://styles/mapb ...

Create a custom button in Material-UI using Styled-components, and integrate it with React

I'm currently working on a project using React, TypeScript, and styled components along with the material-ui library. I have created styled material-ui buttons as shown below: import React from 'react' import styled from 'styled-compone ...

Testing TypeScript using Jasmine and Chutzpah within Visual Studio 2015

I am new to unit testing in AngularJS with TypeScript. I have been using jasmine and chutzpah for unit testing, but I encountered an error "ReferenceError: Can't find variable: angular". My test file looks like this: //File:test.ts ///<chutzpah_r ...