Using Object.keys() with Typescript classes - Developer pitfalls

Using Object.keys() with Typescript classes - Developer pitfalls

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. This is image title Note the penultimate line

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:

function functionNamesShallowWithObjectKeys(object: any): string[] {
  if (object == null) {
    return [];
  }
  return Object.keys(object).filter(key => {
    return (
      typeof object[key] === "function" &&
      excludeMethodNames.indexOf(key) === -1
    );
  });
}

function functionNamesDeep(object: any): string[] {
  let fnMembers: string[] = functionNamesShallowWithObjectKeys(object);

  const proto = Object.getPrototypeOf(object);
  if (proto !== null && proto !== Object.prototype) {
    fnMembers = [...fnMembers, ...functionNamesShallowWithObjectKeys(proto)];
  }
  return fnMembers;
}

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.

function functionNamesShallowWithObjectKeys(object) {
    if (object == null) {
        return [];
    }
    return Object.keys(object).filter(function (key) {
        return (typeof object[key] === "function" &&
            excludeMethodNames.indexOf(key) === -1);
    });
}
function functionNamesDeep(object) {
    var fnMembers = functionNamesShallowWithObjectKeys(object);
    var proto = Object.getPrototypeOf(object);
    if (proto !== null && proto !== Object.prototype) {
        fnMembers = fnMembers.concat(functionNamesShallowWithObjectKeys(proto));
    }
    return fnMembers;
}        
function functionNamesShallowWithObjectKeys(object) {
    if (object == null) {
        return [];
    }
    return Object.keys(object).filter(key => {
        return (typeof object[key] === "function" &&
            excludeMethodNames.indexOf(key) === -1);
    });
}
function functionNamesDeep(object, useObjectKeys = false) {
    let fnMembers = useObjectKeys
        ? functionNamesShallowWithObjectKeys(object)
        : functionNamesShallow(object);
    const proto = Object.getPrototypeOf(object);
    if (proto !== null && proto !== Object.prototype) {
        const functionsOfProto = useObjectKeys
            ? functionNamesShallowWithObjectKeys(proto)
            : functionNamesShallow(proto);
        fnMembers = [...fnMembers, ...functionsOfProto];
    }
    return fnMembers;
}

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.

var Foo = /** @class */ (function () {
    function Foo() {
        this.counter = 0;
    }
    Foo.prototype.increment = function () {
        return ++this.counter;
    };
    Foo.prototype.decrement = function () {
        return --this.counter;
    };
    return Foo;
}());

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().

function functionNamesShallow(object: any): string[] {
  if (object == null) {
    return [];
  }
  return Object.getOwnPropertyNames(object).filter(key => {
    return (
      typeof Object.getOwnPropertyDescriptor(object, key).value ===
        "function" && excludeMethodNames.indexOf(key) === -1
    );
  });
}

function functionNamesDeep(object: any): string[] {
  let fnMembers: string[] = functionNamesShallow(object);

  const proto = Object.getPrototypeOf(object);
  if (proto !== null && proto !== Object.prototype) {
    fnMembers = [...fnMembers, ...functionNamesDeep(proto)];
  }
  return fnMembers;
}

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

Originally published by Sascha Engmann at thecodecampus.de

typescript javascript web-development

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Hire Web Developer

Looking for an attractive & user-friendly web developer? HourlyDeveloper.io, a leading web, and mobile app development company, offers web developers for hire through flexible engagement models. You can **[Hire Web...

Why Web Development is Important for your Business

With the rapid development in technology, the old ways to do business have changed completely. A lot more advanced and developed ways are ...

Important Reasons to Hire a Professional Web Development Company

    You name the business and I will tell you how web development can help you promote your business. If it is a startup or you seeking some...

Hire Dedicated eCommerce Web Developers | Top eCommerce Web Designers

Build your eCommerce project by hiring our expert eCommerce Website developers. Our Dedicated Web Designers develop powerful & robust website in a short span of time.

How long does it take to develop/build an app?

This article covers A-Z about the mobile and web app development process and answers your question on how long does it take to develop/build an app.