如何通知 TypeScript 编译器对 JS 数组原型的扩展?

How to inform TypeScript compiler of extensions to JS Array prototype?

我已经为 JavaScript 数组创建了一个 polyfill;

if (Array.prototype.remove !== 'function') {
    Array.prototype.remove = function (value) {
        var idx = this.indexOf(value);
        if (idx !== -1) {
            return this.splice(idx, 1);
        }
        return false;
    };
}

现在我正在将原始 JavaScript 项目升级为 TypeScript 项目,并且 tsc 抱怨使用 .remove 方法:

class Archive {
   documents: DocInfo[] = [];  // <-- Array of class DocInfo

   addDocument(document: DocInfo) {
      ...
   }

   deleteDocument(document: DocInfo) {
      this.documents.remove(document);
                     ^^^^^^
                     tsc complains here: TS2339:Property 'remove' does not exist on type 'DocInfo[]'
   }
}

如何将此扩展告诉 tsc?

我尝试创建一个类型文件,但没有成功:

declare module 'Array' {
    export function removeByAttr(propertyName: string, propertyValue: any);
}

谢谢

类型应扩展 Array<T> 接口:

interface Array<T> {
    remove(item: T): boolean;
}

使用接口扩展数组 class 这很简单,您可以尝试这样的操作:

Playground

    interface Array<T> {
   remove(o: T): Array<T>;
}

Array.prototype.remove = function (o) {

    var idx = this.indexOf(o);
        if (idx !== -1) {
            return this.splice(idx, 1);
        }
    return this;
}

class DocInfo { 
    name: string ;
    constructor(name) { 
        this.name = name;
    }
}

class Archive {
   documents: DocInfo[] = []; 
   addDocument(document: DocInfo) {
       this.documents.push(document);
   }
   deleteDocument(document: DocInfo) {
      this.documents.remove(document);
   }
   printDocuments() { 
       this.documents.forEach((item: DocInfo) => { 
           console.log(item.name);
       });

   }
}

const a = new Archive();
const _1 = new DocInfo('1');
const _2 = new DocInfo('2');

a.addDocument(_1);
a.addDocument(_2);
a.printDocuments();
a.deleteDocument(_1);
console.log('*********************');
a.printDocuments();
console.log('*********************');
a.addDocument(_1);
a.deleteDocument(_2);
a.printDocuments();