skip to Main Content

A.S.: Object property order in JS is a very complicated topic. For my intents and purposes, only insertion order matters.

TL;DR: Is there a way to declare an object property in JavaScript without giving it a value, so that when the property is set later, it still appears earlier in the insertion order?

const user = { name: unset, age: 42 }


I have a set of asynchronous functions, each returning a value associated with a unique key. They are then invoked in parallel to construct an object with key-value pairs used as entries (properties). Something like this:

const props = {}
const propsSet = getters.map(async ([key, getValue]) => {
  props[key] = async getValue()
})

await Promise.all(propsSet)

return props

Try it.

Sine all of this is asynchronous, the order of properties in props is all over the place: I get sometimes { foo: …, bar: … }, sometimes { bar: …, foo: … }. I could fix that by associating each getter with a sequence number. But a much easier solution is to just initiate the properties as soon as possible; due to how event loop works, this is basically a guarantee that properties of props will be ordered the same as in getters:

const propsSet = getters.map(async ([key, getValue]) => {
    props[key] = null // or any other initialization token
    props[key] = await getValue()
})

In pure JS this a perfectly normal thing to do, but in TypeScript this is usually a compiler error (since arbitrary "initialization token" isn’t assignable to strictly typed properties of props); so, I have to shush the compiler, which I don’t like to do:

values[key] = null! // non-null assertion operator

Try it.

I would prefer if the property is actually not set in the object, but that a "slot" is made available for it. I’ve realized that what I basically need is very similar to declaring variables separately from initializing them, – like in old-school JS style:

var value1, value2

value1 = 42
value2 = 17

Is there any existing or upcoming (proposal) way of declaring object properties in JavaScript without initializing them?

Note that I’m not asking about ways of ordering properties. There are many strategies to do that, including usage of the aforementioned sequence numbers (e.g., array indexes).

2

Answers


  1. One approach could be to first collect the (promises of) key/value pairs, and then call Promise.all on those. Once you get that result, you can construct the object: the key/value pairs will come in their original order:

        const pairs = getters.map(async ([key, getValue]) => [key, await getValue()]);
        return Object.fromEntries(await Promise.all(pairs));
    

    Demo:

    const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
    
    const getters = [
        ["foo", async () => { await delay(100); return 1; }],
        ["bar", async () => { await delay( 50); return 2; }],
    ];
    
    async function getProps() {
        const pairs = getters.map(async ([key, getValue]) => [key, await getValue()]);
        return Object.fromEntries(await Promise.all(pairs));
    }
    
    getProps().then(obj => console.log(JSON.stringify(obj)));
    Login or Signup to reply.
  2. Is there a way to declare an object property without giving it a value?

    No. There are no (type?) declarations at runtime. You can only create an object property, by assignment (in a statement) or initialisation (in an object literal). Either the property exists, with a value1, or it doesn’t exist at all. The default value of variables or properties not set otherwise would be undefined, there is no "unset" value (or absence of a value).

    The idiomatic TS approach to (not) initialise a property as undefined regardless of its declared type would be to use a non-null assertion:

    const propsSet = getters.map(async ([key, getValue]) => {
        props[key] = undefined!;
    //                        ^
        props[key] = await getValue();
    });
    

    But this is basically lying about the type of props, the object is not actually usable until your asynchronous initialisation finishes and its type should reflect that. So rather than asserting Object.create(null) as Record<GroupName, Group> you should use a Partial type, and assert the expected result type only once all properties are actually initialised:

    const groups = Object.create(null) as Partial<Record<GroupName, Group>>;
    //                                    ^^^^^^^
    await Promise.all(Object.entries(groupGetters).map(async ([groupName, getGroup]) => {
        groups[groupName as GroupName] = undefined; // OK now
        groups[groupName as GroupName] = await getGroup();
    }));
    
    return groups as Record<GroupName, Group>;
    //            ^^^^^^^^^^^^^^^^^^^^^^^^^^^
    

    An even better approach however would be to defer the object creation until all the property values are available. That way, no "incomplete" objects exist at any time that need to be typed. In your case, that would be

    return Object.setPrototypeOf(Object.fromEntries(await Promise.all(Object.entries(groupGetters).map(async ([groupName, getGroup]) => 
    //                           ^^^^^^^^^^^^^^^^^^
        [groupName, await getGroup()]
    ))), null) as Record<GroupName, Group>;
    //         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    

    1: Assuming a data property. One can define an accessor property with no getter, or a getter that always throws. You could do this, and subsequently convert it into a data property, but I would advise against that. It is overcomplicated, inefficient, and doesn’t really improve the types either.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search