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

How can a custom event bus from a separate account be incorporated into an event rule located in a different account within the CDK framework?

In account A, I have set up an event rule. In account B, I have a custom event bus that needs to act as the target for the event rule in account A. I found a helpful guide on Stack Overflow, but it was specific to CloudFormation. I am providing another a ...

Tips on capturing JSON data for export and sending it to a specific URL

After implementing the recommended code changes, I still cannot see any updates on the specified WordPress page - . It appears that there may be a login information or other issue preventing me from viewing the changes. Here is the updated code: // New ...

No matter how hard I try, the async function within the React Component keeps returning 'Promise {<pending>}' consistently

Currently, I'm facing an issue where running an asynchronous function inside a functional component in React (NextJS) results in the function returning a pending promise: Promise {<pending>}. Oddly enough, fetching data from a dummy API works pe ...

Error: Unable to parse JSON field value due to an unexpected OBJECT_START

Currently in my coding project, I am utilizing node and mongoose to update a Watson rank and access the database. My goal is to insert multiple documents into the collection. While I can successfully add a single document, I encounter issues when creating ...

Angular throwing an error message: "ChildrenOutletContexts provider not found!"

I developed a basic testing application and encountered the error message - "No provider for ChildrenOutletContexts!" I have searched through various related posts but to no avail. Here is my project structure: The App Module contains the App Routing Modu ...

End the HTML page once the Flash (SWF) animation comes to a close

I have successfully exported my flash file to an HTML page. How can I make the page close automatically once the flash animation is finished? While I can use actionscript to stop the animation, I need the entire page to shut down on its own. I attempted u ...

Whenever I refresh my website after deployment, I encounter an empty error using the MERN stack

Here is a question I previously posted: How can I properly use the res.sendFile for my MERN APP, as I encounter an error every time I refresh, and it was resolved there. I encountered a similar issue here, even after following the same steps that worked b ...

When using Vue2, pushing a string to an array simply replaces the existing string instead of appending it

My current task involves manipulating a local data array by adding and removing strings within a method. However, I have noticed that my logic always results in the array containing only a single string passed to the updateIdArr method. Even after removin ...

Switching Next.js JavaScript code to Typescript

I am currently in the process of transforming my existing JavaScript code to TypeScript for a web application that I'm developing using Next.Js Here is the converted code: 'use client' import React, { useState, ChangeEvent, FormEvent } fro ...

What is the reason behind the lack of exported interfaces in the redux-form typings?

I've been exploring how to create custom input fields for redux-form. My journey began by examining the Material UI example found in the documentation here. const renderTextField = ({input, label, meta: { touched, error }, ...custom }) => < ...

React Intersection Observer Triggering Memory Leaks

Issue Description: I encountered a problem with my React app crashing on mobile. The Chrome dev tools revealed that garbage collection wasn't triggering, and upon inspecting the heap, I found that the top constructors by retained size were all linked ...

Extract a selection from a dropdown menu in ReactJS

I have multiple cards displayed on my screen, each showing either "Popular", "Latest", or "Old". These values are retrieved from the backend. I have successfully implemented a filter option to sort these cards based on popularity, age, etc. However, I am u ...

Guide to setting up Cosmos DB database connection using NestJS version 9.0.0

I'm encountering issues when attempting to include the Cosmos DB connection module in nestjs v9, as I'm facing dependency errors. Nest is unable to resolve the dependencies of the AzureCosmosDbCoreModule (COSMOS_DB_CONNECTION_NAME, ?). Please ens ...

Is there a way to continuously click on a button 99 times or until the code finishes running?

Need Assistance, Please Assist. I am encountering an issue where I have the same type of skip button with identical name and id properties for all products, but only the xpath changes. Can you provide guidance on how to efficiently click on 99 similar ski ...

Sending the id from a component to a service in Angular

In my current project, I am working on a chat application using Angular with WebSocket integration. Let me provide an overview of the architecture I have designed for this project. I created a module called 'chatting' which contains a list of use ...

How come my effort to evade quotation marks in JSON isn't successful?

When trying to parse a JSON-string using the JQuery.parseJSON function, I encountered an error message that read: Uncaught SyntaxError: Unexpected token R. This was unusual as the only uppercase 'R' in my JSON-formatted string appeared right afte ...

What is the best way to make a Firestore request that relies on the initial Firebase response in Next.js?

Is there a way to perform a second cloud Firestore query using the uid obtained in the first query, without the second query executing before receiving the response from the first one? Here's my code: var {data} = useSWR('/api/report', fet ...

Display a popup notification when clicking in Angular 2

Can anyone help me with displaying a popup message when I click on the select button that says "you have selected this event"? I am using Angular 2. <button type="button" class="button event-buttons" [disabled]="!owned" style=""(click)="eventSet()"&g ...

Utilize useMediaQuery for identifying various breakpoints in your design

Currently, I am working on detecting multiple breakpoints in my application to ensure dynamic column generation on a Grid. Although I have managed to accomplish this task, the code appears somewhat repetitive. Is there a method through which I can simpli ...

The error message indicates that the Worklight adapter is an object, not a function

Upon deploying the Worklight adapter to the production server, I encountered an error when the adapter called a Java code from JavaScript: Procedure invocation error. Ecma Error: TypeError: Cannot call property updateProposal in object [JavaPackage com.id ...