-
Notifications
You must be signed in to change notification settings - Fork 12.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Update type definition of Object.keys #17267
Conversation
Solves need to explicitly specify type of `key` when in **Strict Mode**. ## Issue it solves ```ts const someObj = { a: 42, b: 'Hello' } Object.keys(someObj) .forEach(key => someObj[key] // ERROR: Element implicitly has an 'any' type because type ... has no index signature. ) ```
This seems like a small (but important) contribution, so no Contribution License Agreement is required at this point. We will now review your pull request. |
---> /src/lib@ And also, there is already a similar PR, see #17261 (only modify the type of |
Ok sorry for not reading, and thanks for your comment. :/ PR #17261 does not solve this issue, as it just restricts what can be passed to My PR is to link the output type of |
EDIT: overload does nothing in this case.
declare function keys<A>(o: A): (keyof A)[];
declare const x: object;
keys(x); //=> never[]; <------- should be string[] |
See - #15295, |
@@ -236,7 +236,7 @@ interface ObjectConstructor { | |||
* Returns the names of the enumerable properties and methods of an object. | |||
* @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object. | |||
*/ | |||
keys(o: any): string[]; | |||
keys<A>(o: A): (keyof A)[]; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
<A extends {}>
The problem with making Object.keys
return keyof A
is that typescript makes no guarantees that the input object has only the keys that are specified in its type. There may be valid values in the array that are not considered by the type.
@sandersn, can you take a look? |
I think the issue raised in #12253 (comment) still holds: |
Solves need to explicitly specify type of
key
when in Strict Mode.Issue it solves