optional property shorthand in object literal

Optional Property Shorthand in Object Literal

Optional property shorthand in object literal would allow an object to be initialized with potentially null or undefined variables and in the case that the variables are null or undefined they will be omitted from the resulting object. How this differs from the current short hand can be seen in the following example:

Current shorthand:

const a = 1;
let b;  // type is unknown

...

const ourObject = {
  a,
  b
};

When b is null ourObject becomes:

{
  a: 1,
  b: null
}

Optional property shorthand:

const a = 1;
let b;  // type is unknown

...

const ourObject = {
  a,
  b?
};

When b is undefined or null ourObject becomes:

{
  a: 1
}

Background:

Currently when initializing objects with variables of type Maybe the resulting object will still have the ambiguous property with the value of null. There are various ways to handle this but here are a few common ones:

Clean the object

We can use the current short hand and then iterate through the keys and produce a new object with the null properties omitted.

Issues:

  • extra code

Build the object and conditionally add properties

We can create an object with the non ambiguous properties and then conditionally check for the ambiguous properties and add them in:

const ourObject = { a };

if (b) {
  ourObject['b'] = b
}

Issues:

  • easy to reason about but gets too verbose with longer property names
  • lots of optional properties can produce lots of code

Initialize the optional properties in the object using spread

When initializing the object we could spread the result of falsey check and another object with just the ambiguous variable. This way either null gets spread into our final object which means the property is omitted or an object with the value is spread in meaning the property and its value is included:

const ourObject = {
    a: 1,
    ...b && {b}
}

Issues:

  • concise but hard to reason about

just realized I put this in the wrong channel; moving to ideas

update: nm its locked now; if a mod could move this to ideas that would be great

Posts can be moved between topics but i can’t find how to move an entire topic.

I guess it can be left here; if anyone has any feedback I also have this repo:

This could even be extended to all kinds of properties. The following example should result in an empty object:

let undef;
const o = {
    undef?,
    a?: undef,
    ["b"]?: undef
};
1 Like

Ya would also be nice to have a spread like syntax too like maybe:

const test = {
  a: 1,
  b: undefined,
  c: undefined
}

const target = { ...?test } //  { a: 1 }