June 12, 2019

Pitfall using Object.keys() with Typescript classes

In this blog article I would like to describe a stumbling block I stumbled across in my work. TypeScript (TS) is a very good way to increase productivity. The compiler and type system fix many software bugs before they occur. Also the possibility to translate into different versions of ECMAScript (ES) is a useful feature of the TS compiler.

In my TS project there is a help function that should determine the names of all methods of a class and its superclasses. This function worked fine for a target of ES version 5. This function always produced an empty output after I changed the target version to ES 2015.

Let’s take a brief look at how exactly methods of a class are stored in ES. If we use ES classes then the methods of a class will be attached to the prototype of the class.

The original TS code:

In the first step I compared the code of the function that was generated for both target ES versions. To my surprise it was identical except the exchange of the spread operator.

So how could it be that the conversion of the target version caused the code to stop working? The answer is half in the ES standard and half in the original implementation.

In the faulty implementation Object.Keys() was used. This iterates over all enumerable properties of an object. If the code is translated by TS to ES5, the methods are translated into functions. These are then saved as properties to the prototype of the generated constructor function. This write access creates a property that is enumerable.

Unfortunately, according to the ES standard, the methods of a class are stored on their prototype, but they are not enumerable. Consequently Object.keys() cannot iterate over these properties. Fixing the error is quite easy armed with this knowledge. Instead of Object.keys() we work with Object.getOwnPropertyNames() or Object.getOwnPropertyDescriptors().

Conclusion

So you have to be aware that Object.keys()  is not suitable to iterate over properties of classes. Use Object.getOwnPropertyNames()  or Object.getOwnPropertyDescriptors() instead . I hope I could help you to avoid this pitfall.

You can find the complete code on Github https://github.com/sengmann/object-keys-bug.

Related Posts

Sascha Engmann
Developer at thecodecampus </>


Leave a Reply

Add code to your comment in Markdown syntax.
Like this:
`inline example`

```
code block
example
```

Your email address will not be published.