I recently discovered this solution.
declare global { interface ObjectConstructor { typedKeys<T>(obj: T): Array<keyof T> } } Object.typedKeys = Object.keys as any;
This means later on in your code you can do something like this.
for (let key of Object.typedKeys(object)) { object[key] }
Provided we know what type object is it'll work.
object
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.
IOptions
Object.typedKeys(object)
Array<keyof IOptions>
key
keyof IOptions
That's a neat way to go about it! I'm not a fan of monkey-patching builtins, though
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
I recently discovered this solution.
This means later on in your code you can do something like this.
Provided we know what type
object
is it'll work.Looking through the code we can see if
object
is typeIOptions
thenObject.typedKeys(object)
will beArray<keyof IOptions>
meaning an array of keys forIOptions
. Because of this ourkey
gets the typekeyof IOptions
or key forIOptions
.That's a neat way to go about it! I'm not a fan of monkey-patching builtins, though