Object.keys: Return Non-widening literal types for type-inferred objects while maintaining existing behavior for type-assigned objects #60483
Labels
Unactionable
There isn't something we can do with this issue
⚙ Compilation target
ES2015
⚙ Library
dom, es2015, es2016, es2017, ESNext
Missing / Incorrect Definition
Hello, I'd like to discuss Object.keys.
I know there have been many discussions about this topic.
First, I want to clarify that this is not about keyof.
I want to discuss objects with inferred types rather than explicitly assigned types.
The above case shows type assignment.
In cases where the type is inferred like above, we can avoid issues with incorrect keys due to structural typing.
In such cases, I believe we should return Non-widening literal types.
As many have mentioned before, I don't want to discuss keyof.
Here's the type I've designed:
This enhancement would:
For example:
This approach follows a similar pattern to Object.values:
Also, the reason for using
extends string
is that Object always converts keys to strings, excluding symbols. This design decision aligns with Object.keys' behavior of not returning symbols.I propose that objects created through type inference should return Non-widening literal types as demonstrated above. This change would preserve the exact key information available at compile time.
Thank you for considering my proposal regarding Object.keys and Non-widening literal types. This enhancement aims to improve TypeScript's type inference precision while maintaining backwards compatibility with existing code.
I welcome any feedback or suggestions from the TypeScript team and community members. Please let me know if you need any clarification or if there are specific aspects of this proposal that warrant further discussion.
Best regards,
Sample Code
Documentation Link
Referenced specification and implementation:
https://github.com/microsoft/TypeScript/blob/main/src/lib/es2017.object.d.ts
https://tc39.es/ecma262/#sec-topropertykey
I extensively researched issues related to Object.keys. While these discussions are different from my current proposal, they provided valuable context and helped shape my understanding:
Related discussions and issues I've studied:
https://github.com/Microsoft/TypeScript/wiki/FAQ#indirect-excess-properties-are-ok
https://stackoverflow.com/questions/55012174/why-doesnt-object-keys-return-a-keyof-type-in-typescript
Non-widening literal type inferences #24310
Object.keys has wrong return type from 2.1 #12870
Redefine Object.keys to use keyof #20503
Exact Types #12936
The text was updated successfully, but these errors were encountered: