Repository navigation
Support known possible keys in Object.entries and Object.fromEntries #35745
Description
Search Terms
Object.entries, Object.fromEntries
Suggestion
Add
see #12253 (comment)entries<E extends PropertyKey, T>(o: { [K in E]: T } | ArrayLike<T>): [E, T][]; to Object.entries in lib.es2017.object.d.ts
and
fromEntries<K extends PropertyKey, T = any>(entries: Iterable<readonly [K, T]>): { [k in K]: T }; to Object.fromEntries in lib.es2019.object.d.ts
OR
fromEntries<K extends string, T = any>(entries: Iterable<readonly [K, T]>): { [k in K]: T }; extends string for now until #31393 is resolved in terms of the "keyofStringsOnly": true compiler option, which would disallow number and symbol.
#31393 is a related issue that suggests the same addition @ fromEntries
Any other research lead me to #12253 (comment)
Use Cases
Basically, I'd like to map an object with known finite number of fields to an object with the same keys, but where the values are of different type (in the example below - the values are transformed from an object containing label: string and rating: number to number)
Examples
Example repository at https://github.com/wucdbm/typescript-object-entries-key-type
Commenting out the two suggested additions in src/types/es.d.ts leads to two errors in index.ts (Please have a look at the types in src/types/rating.d.ts)
const requestData: BackendRatingRequest = {
stars: Object.fromEntries(
Object.entries(rating.stars).map((v: [RatingFields, RatingWithLabel]) => {
return [v[0], v[1].rating]
})
),
feedback: rating.feedback
};
-
Object.entries(rating.stars).map((v: [RatingFields, RatingWithLabel]) => {RatingFields has no sufficient overlap with string, where because ofrating.stars's index signature, the key can only be one of the values of RatingFields -
Object.fromEntriescomplains that the keys ofRatingFieldsare missing. But in this case, the first element of the returned array can only be of typeRatingFields
I'm leaving the first checklist option unticked. I am unsure whether this wouldn't be a breaking change for TypeScript code in some situations. I personally haven't encountered one, and have had the same es.d.ts file, found in the example repo, in our project, in order to prevent build errors.
Would be nice if someone with more experience in TS's internals had a look at this. Particularly if it woul lead to any regressions.
Checklist
My suggestion meets these guidelines:
- This wouldn't be a breaking change in existing TypeScript/JavaScript code
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
- This feature would agree with the rest of TypeScript's Design Goals.
Activity
MicahZoltu commentedon Dec 18, 2019
The case of
Object.fromEntriesI believe this is different from theObject.keysandObject.entriesproblem. In theObject.keysandObject.entriescase, it would be incorrect for TypeScript to assume that the only keys on the object are limited to those on the type. In the case ofObject.fromEntrieshowever, TypeScript can guarantee that the Object it returns will at least have the set of keys it knows about on the incoming tuple array.Martin Kirilov (@wucdbm) I recommend removing the
Object.entriescase from this request as that cannot change without breaking TypeScript type safety (see the issue aboutObject.keysyou linked). I thinkObject.fromEntriescan be fixed though.dragomirtitian commentedon Dec 18, 2019
Personal stab at typing it, it gets kind of complex, not sure if there is a simpler approach 😕
Playground Link
Or without any helper types (can't wait for the SO questions as to what this does 😂):
Playground Link
wucdbm commentedon Dec 19, 2019
Micah Zoltu (@MicahZoltu) Fair enough.
In that case, I guess the
Object.entriesproblem could be solved by a 3rd-party library that implements runtime extraction based on a type/interface, simply for the sake of not writing these functions by hand.For example,
would generate (once per type) a function that takes an object and returns the fields of
SomeTypeonly by callingObject.entries(object)and then calling.filterto only return the subset contained inSomeType. Or something like that. Assuming the Object.fromEntries proposal is accepted, this would work perfectly well for us, although in our particular case we wouldn't need the.filteroverhead from such a library as the values passed around in our app never satisfy two separate types. At least so far.But then again, this seems to fall outside of the intended use of TypeScript itself.
I stumbled upon https://www.npmjs.com/package/typescript-is and #14419 today. Could use its source code as a starting point if 14419 is accepted and its easy to plug into TS for code generation.
WDYT?
MicahZoltu commentedon Dec 19, 2019
Something similar to
typescript-iscould work for generating code that "loops over all of the keys known at compile time, but not over all of the keys on the object".wucdbm commentedon Dec 19, 2019
Original comment updated.
Furthermore, due to #31393 imo it makes sense to go with
K extends stringrather thanK extends PropertyKeyfor the time being, as that shouldn't hurt anybody, until #31393 is resolved.fromEntries<K extends string, T = any>(entries: Iterable<readonly [K, T]>): { [k in K]: T };Wenzil commentedon Aug 5, 2020
What is the status on this?
fromEntriesseems like it would only benefit from Martin Kirilov (@wucdbm)'s type signature above.MicahZoltu commentedon Aug 6, 2020
Often you can achieve the desired result with a pattern like this:
wucdbm commentedon Aug 6, 2020
Micah Zoltu (@MicahZoltu) Good point. That could come in handy in several of the use-cases the .entries typing proposal was trying to solve.
Does anybody know a use-case where
fromEntries<K extends string, T = any>(entries: Iterable<readonly [K, T]>): { [k in K]: T };will be wrong or interfere with other features or break existing code?alamothe commentedon Jan 25, 2021
Can TypeScript at least provide a type-safe version of
Object.entriesforRecord<K, V>?Here keys are known to be of K, but the current signature treats them as strings.
sdegutis commentedon Aug 20, 2021
Just now I was thinking:
Is that the same feature that this issue is requesting? I was about to make a feature request issue for this use-case.
flying-sheep commentedon Nov 4, 2021
Hi, I was just bitten by this. I very much expected this to work:
CarterLi commentedon Nov 26, 2021
At least this should work:
Its pattern is generally used as a quick implementation of mapValues. Please fix it.
wucdbm commentedon Nov 27, 2021
Do
const obj = {...another}then, should be goodThis is pretty important when mapping the values to something else
CarterLi commentedon Nov 27, 2021
Ok. Then lets make this work
simPod commentedon Jan 20, 2022
Martin Kirilov (@wucdbm) ?
wucdbm commentedon Jan 21, 2022
Simon Podlipsky (@simPod) It has been too long and there are several objections against this, and I've already forgotten whether anything could be done on this matter. I know for sure I made a custom type on one of my projects and that's been long forgotten.
If you have the capacity to carry on, please review and open a new discussion about the part that could be implemented, and check if there aren't any objections against it.
To be fair, given the time span and the fact that JS isn't my primary strength, I can't judge what makes sense at this point, and I don't really have the time or will to get into it.
This has been further fortified by several rejections of contributions towards improving terrible (to say the least) design of (otherwise great) OS libraries, so my will to help anywhere is nowhere to be found these days, sorry.
flying-sheep commentedon Jan 21, 2022
Are there any reasons against making a PR with Titian Cernicova-Dragomir (@dragomirtitian)’s types in #35745 (comment)?
RyanCavanaugh commentedon May 31, 2022
It's not correct to use the input type to determine the output type, because knowing what might be in an array is not the same as knowing what's actually in it. This program is legal per the above definitions but unsound:
niieani commentedon Aug 6, 2022
Ryan Cavanaugh (@RyanCavanaugh) this is true for writeable arrays, but not for const tuples.
Const tuples by definition must include all the the members, and thus guarantee their contents.
Here's a PR with a fix: #50203.
GravlLift commentedon Feb 21, 2023
So I get the hesitancy to use const property keys here. However, I don't understand why the return type is
{k: string]: T}. Given the input type ofIterable<readonly [PropertyKey, T]>, I would expect a return type of{[k: PropertyKey]: T}, no?After all,
Object.fromEntries([[0, "test"]])spits out{0: "test"}.niieani commentedon Feb 22, 2023
Just FYI for anyone following, since my PR with strict typing wasn't accepted due to "too complex", I've finally gotten around to publishing an NPM package with the strict Object.fromEntries typings. It doesn't suffer from any unsoundness as far as I can tell and is fully compatible with the regular Object.fromEntries.
See nesity-types.
wucdbm commentedon Feb 23, 2023
The
radashlibrary hasmapEntriesin case anyone stumbles upon this.adroste commentedon Feb 2, 2024
Martin Kirilov (@wucdbm) Neither
radashnorlodashnorremedaoffer proper type inference (for const values with custom keys).The only working solutions I've found so far (for both directions
entriesandfromEntries) is from StackOverflow https://stackoverflow.com/a/69019874/6292230Quick reminder: code from SO is licensed CC BY-SA (copyleft/viral)
mariusGundersen commentedon Jun 19, 2024
This code is legal in TypeScript today, even though
o.Ais actuallyundefined. So the current definition ofObject.fromentriesis unsound.Object.fromEntries really should return
Partial<{ [k: PropertyKey]: T; }>, since it's not certain what array entries are there.LoganDark commentedon Aug 25, 2024
here is an easy solution for constant entries:
the
T extends Tis needed to distribute over union typesoh and here is one for
Object.entries:scamden commentedon Sep 9, 2024
LoganDark (@LoganDark) thank you! i think this is slightly safer in that it forces a tuple to be passed, which avoids the unsoundness issues mentioned above. It also allows you to pass the tuple inline without adding
as const:LoganDark commentedon Sep 9, 2024
I think here's an
entriesthat works with potentially unbounded arrays and things like that:it's silly. I'm so autistic lmao