Typescript: Change type definition of Object.keys and for..in loop

Created on 18 May 2018  ·  2Comments  ·  Source: microsoft/TypeScript

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:

  • [x] This wouldn't be a breaking change in existing TypeScript / JavaScript code
  • [x] This wouldn't change the runtime behavior of existing JavaScript code
  • [x] This could be implemented without emitting different JS based on the types of the expressions
  • [x] This isn't a runtime feature (e.g. new expression-level syntax)

Most helpful comment

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")[]

All 2 comments

When searching for object.keys I find:

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

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")[]
Was this page helpful?
0 / 5 - 0 ratings

Related issues

zhuravlikjb picture zhuravlikjb  ·  3Comments

fwanicka picture fwanicka  ·  3Comments

blendsdk picture blendsdk  ·  3Comments

dlaberge picture dlaberge  ·  3Comments

DanielRosenwasser picture DanielRosenwasser  ·  3Comments