winglang / wing

A programming language for the cloud ☁️ A unified programming model, combining infrastructure and runtime code into one language ⚡
https://winglang.io
Other
4.97k stars 196 forks source link

Support computed properties in `Json`, `Map` literals #7157

Open Chriscbr opened 5 days ago

Chriscbr commented 5 days ago

Use Case

If you are initializing a new Map or Json object and one if its keys is a variable (not a fixed string), then it's not easy to accomplish today. One way to do it is to create a MutJson object, set an item, and then if want it to be immutable, to use Json.deepCopy, but it's awkward and is inefficient because of the copying involved:

let key = "name";
let x = MutJson {};
x[key] = "wingy";
let y = Json.deepCopy(x);

Proposed Solution

Support computed properties, similar to JavaScript: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#computed_property_names

In Wing this might look like:

let key = "name";
let x = Json {
  [key]: "wingy"
};

An alternative design could be to change Wing's object literal syntax so keys that aren't surrounded by quotes have to refer to variables:

let x = Json {
  key: "wingy" // error: no variable named "key" is defined
};

let key = "name";
let y = Json {
  key: "wingy" // ok
};

But since Wing interoperates with TypeScript, I suspect this would confuse folks and add friction for people switching to Wing, so I recommend against it.

Implementation Notes

No response

Component

Language Design, Compiler

Community Notes

boyney123 commented 4 days ago

Personally coming from TS/JS background I prefer this, FWIT

let key = "name";
let x = Json {
  [key]: "wingy"
};