One of the benefits of JavaScript (and therefore TypeScript) is being able to do whatever you want with objects. This can be dangerous, of course, because of type promiscuity – which is one thing that TypeScript addresses.
Object.keys
Sometimes it is still useful to just loop through each property on an object in order to do something. I find that I use it for unit testing, but there’s other applications, too. Object.keys allows you to enumerate the properties of an object, returning you an array of string which represent the property names. You can then, if you want to, use the square bracket operator to reference that property on the object.
<script src=”https://gist.github.com/Flayed/9578d0f9dca9242bde7710fbaa2becf4.js”></script>
Gotcha
One gotcha is that even if you define a type in TypeScript, Object.keys will only enumerate defined values.
<script src=”https://gist.github.com/Flayed/75212850265b3063243464ce5308bf7a.js”></script>
This makes sense, since interfaces in TypeScript are only used at compile time for type checking. At the end of the day, your TypeScript is transpiled to JavaScript, and interfaces are unnecessary since JavaScript does whatever the flippidy-dip it wants at runtime.