admin管理员组

文章数量:1134246

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).

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).

Share Improve this question edited Jan 7 at 21:55 jcalz 326k29 gold badges434 silver badges436 bronze badges asked Jan 7 at 19:17 Parzh from UkraineParzh from Ukraine 9,8354 gold badges46 silver badges80 bronze badges 8
  • 1 This is asking about a runtime feature, right? You want to be able to "declare" a property for insertion ordering without actually inserting anything. This isn't really a TS question, then, am I right? (Aside: please edit to change your TS code to values[key] = null! and not //@ts-expect-error, since the latter is a sledgehammer, silencing all errors, even syntax errors, whereas all you're trying to do is a type assertion. Talking about error suppression is sort of a red herring here anyway, if you care about a runtime feature.) Could you edit to make this clear? – jcalz Commented Jan 7 at 19:34
  • Yes, it is not a typescript question indeed. Typescript is only used to demonstrate the problem quicker. I'll edit it when I have a chance. Or you could edit it yourself. – Parzh from Ukraine Commented Jan 7 at 20:55
  • 1 I tried to edit it to the best of my ability, to demonstrate that what you really want is a way for an object property in JS to be "allotted" but not initialized. – jcalz Commented Jan 7 at 22:00
  • Anyway the answer to this question is going to be "no, there is no way to do this, and no proposal to do so being considered anywhere". – jcalz Commented Jan 7 at 22:04
  • Since the old-school var value1; is equivalent to var value1 = undefined;, why can't you just create the object with all the properties being undefined, const props = {key1: undefined, key2: undefined, ...} – Barmar Commented Jan 7 at 22:04
 |  Show 3 more comments

1 Answer 1

Reset to default 1

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.

本文标签: javascriptIs there a way to declare an object property without initializing itStack Overflow