EDIT:
I opened an issue related to this on github: https://github.com/Microsoft/TypeScript/issues/21265
It seems that{ ...other: xother }
is not valid JS, neither TS, code and it should not even compile.
Original question:
Let's assume the following example:
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 for property a
.
Is it valid, according to TypeScript specs, to do the same with the remaining properties ...other
? Something like:
const { a: va, b: vb, ...other: vother } = values;
I know it works, I've tested it (online test). But I'm unable to find where it's defined to do so.
The examples of the documents that refers to property renaming always show the "normal" case: TypeScript Handbook - Variable Declarations. And the spec grammar refres to a BindingPattern
that's no described (or I've missed) in the spec: TypeScript Spec.
My first impression is that it is not very useful since ...other
is already a custom variable name. But it works. And I'm curious to know where it is specifically defined or if it's only a corner case that works (I suppose not).
The handbook link you mention covers most of the scenarios you have in your example under destructuring, but I think the one situation it covers is not explicitly covered (only implicitly).
The particular feature you are referring to (I think) is the combination of:
You can create a variable for the remaining items in an object using the syntax
...
:
and
You can also give different names to properties:
The handbook doesn't give an example where both are used, as shown below. The interesting part of this combined use is that the ...other
token doesn't actually mean anything and is never referenced (or referenceable). In the "working" version of the below example, without the erroring line, the other
token doesn't appear in the output at all.
Here is the shortened example:
const values = { a: "1", b: "2", c: "3", d: "4" };
const { a: one, ...other: twoThreeFour } = values;
console.log(other); // ERROR there is no variable 'other'
console.log(a, twoThreeFour); // OK
And the version without the error - the transpiled JavaScript has no reference to other
anywhere in the code:
const values = { a: "1", b: "2", c: "3", d: "4" };
const { a: one, ...other: twoThreeFour } = values;
console.log(a, twoThreeFour); // OK
There is an issue to improve the clarity of the use of rest elements in relation to destructuring in the underlying language specification.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With