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 | Show 3 more comments1 Answer
Reset to default 1Is 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
版权声明:本文标题:javascript - Is there a way to declare an object property without initializing it? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736780147a1952549.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
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:34var value1;
is equivalent tovar 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