【问题标题】:Array extension code results in error "The "this" keyword is disallowed outside of a class body" in TypeScript tslint数组扩展代码在 TypeScript tslint 中导致错误“在类主体之外不允许使用“this”关键字”
【发布时间】: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


【解决方案1】:

让我们改为扩展 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
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多