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

Typescript, monkey-patching an Array instance (not global)

假设我有一个数组

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

现在假设我想向这个数组添加属性

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

我收到了"Property 'sum' does not exist on type 'number[]'"

如何在 Typescript 中执行此操作?

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

// 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() { ... };

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