原型函数未定义NodeTS



我正试图在Array上添加一个原型函数,并在Node项目中的.d.ts文件中声明如下,但仍在获得"paginate不是函数";但是当我尝试在数组变量上访问此方法时,VSCode不会返回任何错误。

declare global {
interface Array<T> {
paginate(filters: Object): Array<T>;
}
}
Array.prototype.paginate = function(f): Array {
console.log("PAGINATE !!");
return this;
}
export {};

我希望能够访问这个";paginate";方法在我的整个项目中全局导入,而不在每个文件中导入

您只需要将原型和类型声明放在一个文件上,然后将其导入到您的入口文件(例如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);
};

不是你问题的答案,但我仍然认为这是一个值得补充的问题。您可以创建自定义类来扩展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游乐场

最新更新