Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the cleanest way to tell typescript that each element of Object.keys(foo) is really a key of foo?

Tags:

typescript

playground

const foo = {
  a: 1,
  b: 2,
  c: 3
};

Object.keys(foo).forEach(key => {
  foo[key]++; // error: expression of type 'string' can't be used to index ....
})

There must be multiple ways to solve it. I'm looking for a recommended way with least impact on readability. Thanks!

==========

Edit:

Bonus: would be great if I can still have autocompletion when I type foo. in my codebase.

like image 215
Quuxuu Avatar asked Oct 15 '25 15:10

Quuxuu


1 Answers

This should work:

(Object.keys(foo) as (keyof typeof foo)[]).forEach(key => {
    foo[key]++;
})

This isn't automatically done for you, because in theory it could be unsafe, but I played with various scenarios and couldn't produce a working demo with a runtime error.

like image 81
ZYinMD Avatar answered Oct 21 '25 02:10

ZYinMD



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!