Search code examples
javascriptnode.jstypescripttsc

Array Prototype will included in the List of the Array


I am using typescript to add in new prototype in the Array. I found out that i am able to print out the prototype function in the for loop.

.ts

declare global {
  interface Array<T> {
    group(groupByKey: T): Array<T>;

  }
}

if (!Array.prototype.group) {
  Array.prototype.group= function<T>(this: T[], groupByKey: string): T[] {
    return group(this, groupByKey);
  };
}

console

var keys = Object.keys({a:1});
var str=""
    for (var k in keys) { 
        console.log(k)
    }

The console output is

0 
group

is it possible to print out the value in array instead of prototype value. But prototype can function well too.


Solution

  • You are seeing the function name because it is defined as enumerable property. You can change how you define it to fix this:

    Object.defineProperty(Array.prototype, "group", {
      value: function<T>(this: T[], groupByKey: string): T[] {
        return group(this, groupByKey);
      },
      enumerable: false, // <-- important part
      configurable: true,
      writable: true
    });