原型函数未定义 NodeTS

Prototype function undefined NodeTS

我正在尝试在 Array 上添加原型函数,并已在我的 Node 项目的 .d.ts 文件中声明如下,但我仍然收到“分页不是函数”,但 VSCode当我尝试在数组变量上访问此方法时没有返回任何错误。

declare global {
    interface Array<T> {
        paginate(filters: Object): Array<T>;
    }
}

Array.prototype.paginate = function(f): Array {
    console.log("PAGINATE !!");
    return this;
}

export {};

我希望能够在我的整个项目中全局访问这个“分页”方法,而无需在每个文件中导入它

您只需要将原型和类型声明放在一个文件中,然后将其导入您的入口文件(例如index.ts),然后您就可以在任何地方使用它了。

例如,目录如下所示

.
└── src
    ├── index.ts
    ├── arr.ts
    └── other.ts

arr.ts

declare global {
  interface Array<T> {
    paginate(filters: Object): Array<T>;
  }
}

Array.prototype.paginate = function (f) {
  console.log("PAGINATE !!");
  return this;
};

export {};

然后在你的 index.ts

import "./arr";
import otherFile from "./other";

otherFile();

并在 other.ts

export default () => {
  [].paginate(5);
};

不是您问题的真正答案,但我仍然认为这是一个值得补充的内容。您可以创建自定义 class 来扩展 Array,然后实现您自己的方法,而不是扩展原型

class PaginatedArray<T> extends Array<T> {
  currentPage = 0;
  perPage: number;

  constructor(perPage: number) {
    super();
    this.perPage = perPage;
  }

  next() {
    this.currentPage++;
    return this.getCurrentPage();
  }

  previous() {
    if (this.currentPage > 0) this.currentPage--;
    return this.getCurrentPage();
  }

  gotoPage(page: number) {
      this.currentPage = page < 0 ? 0 : page;
      return this.getCurrentPage();
  }

  getCurrentPage() {
    const start = this.currentPage * this.perPage;
    return Array.from(this.slice(start, start + this.perPage));
  }
}

const arr = new PaginatedArray<number>(2);

for (let i = 1; i < 10; i++) arr.push(i);

console.log(arr.getCurrentPage()); // [1, 2]
console.log(arr.next()); // [3, 4]
console.log(arr.next()); // [5, 6]
console.log(arr.next()); // [7, 8]
console.log(arr.next()); // [9]
console.log(arr.gotoPage(1)); // [3, 4]
console.log(arr.previous()); // [1, 2]

TS Playground