我正在尝试在Typescript中向Array对象添加一个方法.我已经在SO上找到了其他解决方案,但这些都不适用于我.
我的代码看起来像:
interface Array {
average(): () => number;
}
Array.prototype.average = () => {
var sum: number = 0
for (var i = 0; i < this.length; i++)
sum += this[i]
if (this.length)
return sum / this.length
return 0
}
Run Code Online (Sandbox Code Playgroud)
我收到错误: The property 'average' does not exist on value of type 'Array'
您是否只在Visual Studio中出错?由于扩展内置接口的错误,预计会有这么多.如果您只是调用tsc.exe,这应该有效.
相关地,你的代码有点偏离 - 你的声明average
描述了一个函数,它返回一个返回一个数字的函数,而不是返回一个数字(你想只写average(): number
那行).此外,因为您在实现中使用=>
而不是在运行时function() {
绑定到错误的this
值.希望有所帮助!
这是非常简单的解决方案(使用 typescript 1.6 测试):
1) 使用 Array 类型定义方法:
interface Array<T> {
average():number;
}
Run Code Online (Sandbox Code Playgroud)
2)实现方法:
Array.prototype['average'] = function () {
return this.reduce(function (a, b) {
if(typeof a !== "number" || typeof b !== "number"){
throw new Error("avg method applies only on numeric arrays.");
}
return a + b;
}, 0) / this.length;
};
Run Code Online (Sandbox Code Playgroud)
呈现的代码应该是:
Array.prototype.average = function()........
Run Code Online (Sandbox Code Playgroud)
现在您可以将其称为:
var arr:number[] = [1, 2, 3, 4, 5, 6];
arr.average()
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3630 次 |
最近记录: |