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.fromEntries
complains that the keys ofRatingFields
are 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.