tc39 / proposal-optional-chaining

https://tc39.github.io/proposal-optional-chaining/
4.94k stars 75 forks source link

should allow for deep-setting values the same way #85

Closed jonapgar closed 5 years ago

jonapgar commented 5 years ago

This is really a different but highly related feature. I have always thought it would be great to be able to safely deep set values

  let config = {}
  config?.some.deep.property = 'foo'

When a property is not present on the object, it is created as an object {}.

  {"some":{"deep":{"property":"foo"}}}
ljharb commented 5 years ago

What about in objects that aren’t “plain objects”, like null objects, proxies, or things with an inheritance tree - what if the type to be created wasn’t {}?

phaux commented 5 years ago

I would expect that to be equivalent to something like:

let config = {}

if (config != null) {
  config.some.deep.property = "foo"
}

This is how optional assignment in CoffeeScript works.

dusave commented 5 years ago

In that example, config is an empty object, so it would error when trying to set some. If you did ?. the whole way up the chain, it might make more sense, but @ljharb still has a lot of great points.

claudepache commented 5 years ago

See also #72.

There seems to be disagreement on whether the syntax should mean “optional assignment” as in #18, CoffeeScript and Swift, or “forced assignment” (i.e., creating missing intermediate objects) as proposed here and in #72...

BridgeAR commented 5 years ago

This could probably be brought up in a separate proposal? It does not seem to be directly related to optional-chaining.

silicakes commented 5 years ago

I think it's a bad idea, unless you'll force everything that's undefined along the way to be something specific, i.e {}, which might not be suited for functions, arrays, proxies and so on.

jonapgar commented 5 years ago

Granted it should probably be a totally separate proposal but I thought the syntax could be harmonious as there is an inverse relationship between assignment and access.

@claudepache thanks for pointing out #72, #18 I will close this in favour of those issues