DEV Community


Discussion on: Indexing objects in TypeScript

link2twenty profile image
Andrew Bone • Edited

I recently discovered this solution.

declare global {
  interface ObjectConstructor {
    typedKeys<T>(obj: T): Array<keyof T>
Object.typedKeys = Object.keys as any;
Enter fullscreen mode Exit fullscreen mode

This means later on in your code you can do something like this.

  for (let key of Object.typedKeys(object)) {
Enter fullscreen mode Exit fullscreen mode

Provided we know what type object is it'll work.

Looking through the code we can see if object is type IOptions then Object.typedKeys(object) will be Array<keyof IOptions> meaning an array of keys for IOptions. Because of this our key gets the type keyof IOptions or key for IOptions.

mapleleaf profile image
MapleLeaf Author

That's a neat way to go about it! I'm not a fan of monkey-patching builtins, though