【发布时间】:2020-07-24 20:41:13
【问题描述】:
我在 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
我不明白我的代码有什么问题。
有人可以给我建议吗?
【问题讨论】:
-
您不应该修改原生“类”,如 Object、Array、Function 等。这是一种不好的做法。
-
问题不在于代码,而在于 tslint 规则。您可以在这种情况下或一般情况下禁用它 - 取决于您是否觉得它有用
标签: typescript tslint