Proposal idea: binding object/array and properties/elements in function argument at the same time

Hi all.

Haskel uses @ symbol to bind the value and its components at the same time, in JS it would look this way:

function f(obj@{foo, bar}) { ... }

The above would create 3 bindings - the whole object obj and properties foo and bar

In Haskell it improves ergonomics of writing code a lot - if I started with the pattern and then later realised that I need the whole thing, I can just add the name to the front, without moving pattern to another binding, creating unnecessary noise in diff (in some cases in JS code it moves back and forth several times).

It seems simple and trivial, but switching between Haskell and TypeScript this is one thing I miss most in Typescript - having ability to bind objects and their members in one binding is very convenient.

Symbol "@" in JS is probably best reserved for decorators, even if not needed in this context...

Some semantically meaningful options could be "." and "?." to allow binding (and optionally binding) properties and elements in arguments:

function f(obj.{foo, bar}, tuple?.[x, y]) { ... }

What do you think?

1 Like

https://github.com/zkat/proposal-as-patterns may be relevant.

2 Likes

Yes - missed it!
Syntax aside, it solves the same problem, in a more verbose way though (and may clash with "as" in typescript...).

On syntax, it's

const {x: {y} as x} = {x: {y: 1}} // in the proposal

vs

const {x.{y}} = {x: {y: 1}}

Having a bigger thing in front of smaller matches the rest of the syntax, "as" looked a bit confusing at first. We can get used to either of course. Should I put the comment there?

Thank you!

I'd like the shorter syntax proposed here, also as location confuses me, it could be hard to read on a more complex objects with longer names, like:

const {userProperties: {identifier, absoluteUrl, somethingElse} as userProps} = someObject

As opposite current syntax allows to see the new name next to property it renames:

const {userProperties: userProps.{identifier, absoluteUrl, somethingElse}} = someObject

So I think this proposal solves the problem with more efficiency.