Changing the names of the remaining variables while object destructuring in TypeScript

UPDATE:

I have created an issue regarding this topic on github: https://github.com/Microsoft/TypeScript/issues/21265
It appears that the syntax { ...other: xother } is not valid in JavaScript or TypeScript, and should not compile.

Initial Query:

Consider the following scenario:

const values = { a: "1", b: "2", c: "3", d: "4" };
const { a: va, b: vb, ...other } = values;

where a new variable name va is assigned to property a.

According to TypeScript specifications, is it permissible to do the same with the remaining properties using ...other? Like so:

const { a: va, b: vb, ...other: vother } = values;

It has been verified to work (online test). However, I am unable to locate where this behavior is officially specified.

The examples provided in the documentation typically demonstrate property renaming in a more standard manner: TypeScript Handbook - Variable Declarations. The specification grammar references a BindingPattern which may not be clearly defined in the spec: TypeScript Spec.

My initial assumption is that this syntax might not be very practical since ...other already serves as a custom variable name. Nonetheless, it functions as expected. I am intrigued to understand the specific definition behind it or if it is merely a working exception (which I doubt).

Answer №1

The link provided in the handbook you mentioned does cover most of the scenarios illustrated in your example regarding destructuring. However, it seems that a particular situation is only implicitly covered and not explicitly outlined.

Specifically, the feature you are highlighting involves the combination of:

Creating a variable for the remaining items in an object using the syntax ...:

as well as

Assigning different names to properties.

While the handbook doesn't provide an example where both aspects are utilized together, it's worth noting that the ...other token in this scenario remains unused and unreferenceable. In the corrected version presented below, excluding the erroneous line, the other token does not appear in the output at all.

Here's a condensed version of the example:

const values = { a: "1", b: "2", c: "3", d: "4" };

const { a: one, ...other: twoThreeFour } = values;

console.log(other); // ERROR no 'other' variable exists
console.log(a, twoThreeFour); // OK

In the error-free version - after transpilation to JavaScript, there is no mention of the other variable throughout the code:

const values = { a: "1", b: "2", c: "3", d: "4" };

const { a: one, ...other: twoThreeFour } = values;

console.log(a, twoThreeFour); // OK

An issue has been raised to enhance the clarity surrounding the use of rest elements in relation to destructuring within the language specification.

Answer №2

When it comes to destructuring variables, feel free to use any name other than other. Here's an example to demonstrate:

const {...rest} = someVaribale;
const {...myname} = otherVariable;

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 is the method for incorporating opacity into the background color CSS attribute using a Fluent UI color?

Currently, my challenge involves applying opacity to a background color sourced from the fluent UI library, which utilizes Design Tokens. Typically, I would add opacity to a background color like this: background-color: "rgba(255, 255, 255, 0.5)" However ...

Turn a textfield on and off in real-time

Hey everyone, I've been working on making a textfield dynamic and I wanted to share my code with you: <input type="text" id="test1" value ="dynamic" onfocus="this.disabled=true" onblur="this.disabled=false"> <input type="text" id="test2 ...

Leveraging jQuery's .when and .then methods allows for

I'm attempting to utilize a shared ajax function that is meant to retrieve the value returned from the PHP script. function fetchAjax(url, data, type) { result = 0; $.when( $.ajax({ type: "POST", url: url, data: data, ...

Ways to automatically refresh a page in Javascript after a short period of user inactivity

Similar Question: How Can I Modify This Code To Redirect Only When There Is No Mouse Movement I am looking to update a web page automatically if the user is inactive, specifically through key presses or mouse clicks using Javascript. ...

What is the process of connecting two models in Mongoose?

In this scenario, we have two models - ProductModel and CategoryModel. The goal here is to establish a connection between creating a product (ProductModel) and assigning it to a category. The issue arises when the category field is not getting filled in t ...

Retrieving multiple raw markdown files from GitHub using React JS

Currently, I am facing a challenge in fetching data from multiple raw .md files stored in different folders within a GitHub repository. Although I have successfully retrieved data from one file, my goal is to access all of them. The situation involves a G ...

Loading input datalist in Firefox postponed

My goal is to implement an input field for a username that allows users to select from a wide range of names/usernames. I want them to be able to enter a partial string from the name or username. Instead of loading the entire list initially, I aim to load ...

Form Input Field with Real-Time JavaScript Validation

Is there a way to validate the content of a textarea using pure JavaScript, without using jQuery? I need assistance with this issue. <script> function validate() { // 1. Only allow alphanumeric characters, dash(-), comma(,) and no spaces ...

Tips for avoiding the transmission of className and style attributes to React components

Hey there! I'm working on a custom button component that needs to accept all ButtonHTMLAttributes except for className and style to avoid any conflicts with styling. I'm using TypeScript with React, but I've run into some issues trying to ac ...

Dynamic manipulation of classes based on user attributes

One thing I've noticed is that certain WordPress themes, like 'Thematic', include user-specific classes in the body element to avoid using CSS browser hacks. For example: wordpress y2010 m02 d26 h05 home singular slug-home page pageid-94 pa ...

Does Leaflet.js provide a method to cycle through all markers currently on the map?

Is there a way to make my map icons scale in size with zoom instead of being a static 38x38? If CSS can achieve this, I'm open to that option as well. It seems like it would also involve iterating through all markers, but I haven't been able to f ...

Is there a more efficient method for translating arrays between JavaScript and PHP?

Currently, I am in the process of developing a web page that has the capability to read, write, and modify data stored in a MySQL database. My approach involves utilizing PHP with CodeIgniter for handling queries while using JavaScript to dynamically updat ...

Dynamically attach rows to a table in Angular by triggering a TypeScript method with a button click

I need help creating a button that will add rows to a table dynamically when pressed. However, I am encountering an error when trying to call the function in TypeScript (save_row()). How can I successfully call the function in TypeScript and dynamically a ...

Steps to make ng-packagr detect a Typescript type definition

Ever since the upgrade to Typescript 4.4.2 (which was necessary for supporting Angular 13), it appears that the require syntax is no longer compatible. Now, it seems like I have to use this alternative syntax instead: import * as d3ContextMenu from ' ...

What is the best way to implement a CSS Style specifically for a glyphicon icon when it is in keyboard focus?

I have a particular icon representing a checkbox that appears as a glyphicon-star. It is designed to display in yellow when focused on by the keyboard navigation. This feature is intended to help users easily identify their location on a page. However, an ...

Issue with updating input value during keyup event in Android Chrome specifically

Check out this straightforward jsfiddle: https://jsfiddle.net/gq9jga4q/33/ <input type="text" id="kbdhook" /> <div id="result" >1: </div> <div id="result2" >2: </div> <div id="result3" >3: </div> $('#kbdh ...

Authentication Redirect Failure when using Passport to an absolute URL

I am looking to redirect the user to a different URL with the code/token received after logging into Facebook using Passport in Express.js. app.get('/auth/facebook/callback', function (req, res, next) { var authenticator = passport.authentic ...

Having trouble with Javascript files failing to load while hosting a website on digital ocean?

Recently, I developed a web application using an express backend and the ejs view engine. Everything works perfectly fine when tested on my local machine. However, I encountered issues when trying to host it on a digitalocean droplet (Ubuntu 22.10 x64). Af ...

PHP: How to Return a Multidimensional Array and Separate Variables Simultaneously

I am trying to send a 2D array with multiple individual variables from a PHP script to a JavaScript client using AJAX. Despite many attempts, I haven't been able to figure out how to include additional individual variables (like $var1, $var2, $var3) i ...

What is the way to assign a variable to ngClass in Angular?

I'm currently working on creating modals that will display different content based on which button is clicked. Each button should trigger a unique modal to appear, each with its own specific content inside. When a button is clicked, the 'active&a ...