Initializing get/set accessor without method syntax?

I often create an “uninitialized” object of following form:

const uninitialized = () => {
  throw new Error("Uninitialized");
};

const obj = {
  get foo() {
    return uninitialized();
  },
  get bar() {
    return uninitialized();
  },
  get baz() {
    return uninitialized();
  }
};

What if we could write like following; this is shorter, more straightforward and slightly memory efficient.

const obj = {
  get foo: uninitialized,
  get bar: uninitialized,
  get baz: uninitialized,
};

This pattern often appears when I want to make TypeScript happy where I have to supply an object that has specific shape but is not initialized yet.

Here's some previous discussion on this topic: Allow arrow functions getters

I wonder if decorators could also help here, especially if TypeScript added support for having the decorator participate in the typing Implement the updated JS decorators proposal · Issue #48885 · microsoft/TypeScript · GitHub

2 Likes

You could do

const uninitialized = {
  get() {
    throw new Error("Uninitialized");
  },
  enumerable: true,
  configurable: true,
};
const obj = Object.defineProperties({}, {
  foo: uninitialized,
  bar: uninitialized,
  baz: uninitialized,
});
1 Like