如何将原型方法添加到Angular2中的所有数组?

时间:2016-02-14 16:31:38

标签: angular

我已经创建了一个用于对数组中的值求和的函数,我想将其添加为所有数组的原型。但是我收到以下错误:

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[]'.

应用/ 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;           
};  

应用/ main.ts

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

bootstrap(TrainingComponent);

1 个答案:

答案 0 :(得分:0)

创建一个类让我们说MyCustomArray.ts

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

无论何时你想使用, 制作MyCustomArray的对象。

_customArrayObj=new MyCustomArray<String>();