1

I have created a function for summing values from an array and I want to add it as prototype for all arrays. But I get the following error:

app/training.ts(30,48): error TS2339: Property 'sum' does not exist on type 'Exercise[]'.
[0] app/training.ts(41,41): error TS2339: Property 'sum' does not exist on type 'Exercise[]'.

app/array.ts

export interface Array<T> {     
  sum:(exp?:(item)=>number)=>number;     
}     

Array.prototype['sum'] = function (exp?:(item)=>number){     
    var result = 0;     

    this.map(exp || ((item) => item)).forEach( (val) => result += val);     

    return result;           
};  

app/main.ts

import {bootstrap}    from 'angular2/platform/browser'
import {Array} from './array';
import {TrainingComponent} from './training.component'

bootstrap(TrainingComponent);
Fran b
  • 3,016
  • 6
  • 38
  • 65

1 Answers1

0

Create a Class lets Say MyCustomArray.ts

export class MyCustomArray extends Array<T>{
  //all methods u want to add on array.   
   sum(){
  //ur logic goes here 
  }
}

And whenever u want to use , Make a object of MyCustomArray.

i.e

_customArrayObj=new MyCustomArray<String>();
Parth Ghiya
  • 6,929
  • 2
  • 30
  • 37