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

问题描述 投票:0回答:1

假设我有一个数组

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

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

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

我收到“属性'总和'不存在类型'号[]'”

我怎么在打字稿中这样做?

typescript typescript-typings typescript2.0
1个回答
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() { ... };

如果它是一次性的,我会在大多数时间做第一次。

© www.soinside.com 2019 - 2024. All rights reserved.