This is another proposal for rebinding destructured properties to an object.
The goal is to provide an alternative syntax for the "as" proposal, based on the "operator restructuring" proposal syntax.
This proposal can also be related to this other one.
Destructuring assignement
const obj = { a: 1, b: 2, c: 3 };
const newObj.{ a, b: newB } = obj;
console.log(a); // 1
console.log(newB); // 2
console.log(newObj); // { a: 1, newB: 2 }
Function parameter destructuring
const obj = { a: 1, b: 2 };
function doSomething (obj.{ a, b: newB, c = 3 }) {
console.log(a); // 1
console.log(newB); // 2
console.log(c); // 3
console.log(obj); // { a: 1, newB: 2, c: 3 }
}
doSomething(obj);
Using with imports
import obj.{ a, b as newB } from './obj.js';
console.log(a); // 1
console.log(newB); // 2
console.log(obj); // { a: 1, newB: 2 }
Pros and Cons
pros:
- object name placed before its properties
- no conflict with Typescript
as
operator
cons:
- It might not be clear at first glance what we're doing with this syntax. Maybe because we are not used to it yet? I'd need your feedback on this point! :)
Array syntax
Also, we need to see if we can (and should) extend this proposal for arrays.
Array destructured property rebinding seems less useful compared to objects.
Here is how it would look like:
/* Array destructuring */
const arr = [1, 2, 3];
const newArr.[a, b] = arr;
console.log(a); // 1
console.log(b); // 2
console.log(newArr); // [1, 2]
/* Function parameter destructuring */
const arr = [1, 2];
function doSomething (arr.[a, b, c = 3]) {
console.log(a); // 1
console.log(b); // 2
console.log(c); // 3
console.log(obj); // [1, 2, 3]
}
doSomething(arr);
/* No use case for imports */
First, I'd like to point out that the syntax .[]
is very close to the optional chaining operator ?.[]
syntax. This could potentially create confusion among programmers.
Also, I can't really think of a pertinent use case for using this syntax on arrays. But maybe others will :)
Feel free to share your thoughts about this proposal, especially about array destructured property rebinding!
(also if you can come with a better name than "destructured property rebinding" that would be great )