2016-02-14 34 views
1

我已經創建了一個從數組求和值的功能,我想將其添加爲原型的所有陣列。但我得到以下錯誤:如何將原型方法添加到Angular2中的所有數組?

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); 
+0

貌似http://stackoverflow.com/questions/14000645/how-to-extend-native-javascript-array-in-typescript的DUP –

回答

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>(); 
相關問題