打字稿,猴子修补数组实例(非全局)

时间:2017-05-14 07:40:18

标签: typescript typescript-typings typescript2.0

假设我有一个数组

const myArray = [1,2,3,4]

现在假设我要为此数组添加属性

myArray.sum = function(){return this.reduce( (a:number,b:number)=>a+b )}

我收到"财产'总和'类型'数字[]'"

上不存在

如何在打字稿中执行此操作?

1 个答案:

答案 0 :(得分:2)

有两种方法可以做到这一点:

// ignore types
(myArray as any).sum(...);

// patch it
interface X extends Array<number> {
  sum(...): number
}
const myArray: X = [1,2,3,4] as X
myArray.sum = function() { ... };

如果是一次性的,我会在大部分时间做第一次。