Skip to content
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

Change type definition of Object.keys and for..in loop #24243

Closed
4 tasks done
Austaras opened this issue May 18, 2018 · 2 comments
Closed
4 tasks done

Change type definition of Object.keys and for..in loop #24243

Austaras opened this issue May 18, 2018 · 2 comments

Comments

@Austaras
Copy link

Austaras commented May 18, 2018

Search Terms

Object.keys, index signature

Suggestion

Currently the definition of Object.keys in lib.d.ts is

keys(o: {}): string[];

why not change to

keys<T extends Object>(o: T): Array<keyof T>

and accordingly change for ... in loop

Use Cases

It is ridiculous that code like
const a = {}
Object.keys(a).forEach(key => a[key])
will raise a 'has no index signature' error

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. new expression-level syntax)
@MartinJohns
Copy link
Contributor

When searching for object.keys I find:

#20853, #20503, #19765, #19448, #15627, #15570, #15295, #13254, #12870, #12314.

@ducin
Copy link

ducin commented Jul 15, 2018

Yep, that works out of the box:

const getKeys = <T extends {}>(o: T): Array<keyof T> => <Array<keyof T>>Object.keys(o)
var keys = getKeys({ first: "John", last: "Lennon" }) // => ("first" | "last")[]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants