数组扩展代码导致错误"The " TypeScript tslint 中的此" keyword is disallowed outside of a class body"



我在TypeScript中编写了以下数组扩展方法代码。

interface Array<T> {
divideInto(n: number): Array<T[]>
}
Array.prototype.divideInto = function<T> (n: number): T[][] {
const items = this as T[];
if (n < 1) {
return []
}
const arrList = []
let index = 0
while (index < items.length) {
arrList.push(items.slice(index, index+n))
index += n
}
return arrList
}

当我构建此代码时,TSLint会显示以下错误消息。

the "this" keyword is disallowed outside of a class body

我不明白我的代码中有什么问题。

有人能给我建议吗?

让我们扩展Array类:

class AugmentedArray<T> extends Array<T> {
divideInto(n: number):T[][] {
const items = this
if (n < 1) {
return []
}
const arrList = []
let index = 0
while (index < items.length) {
arrList.push(items.slice(index, index+n))
index += n
}
return arrList
}
}

相关内容

最新更新