2016-11-17 5 views
0

Я создал полипол для JavaScript-массива;Как проинформировать компилятор TypeScript о расширении к прототипу JS Array?

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 к проекту машинописи и 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[]' 
    } 
} 

Как я могу сказать ТСК об этом расширении?

Я попытался создать файл типизации, но без какого-либо успеха:

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

Благодарности

+0

Почему бы не сделать его частью 'DocType'. – Rajesh

+0

Метод удаления должен быть частью «Массив» DocType. Не на самом DocType! – mvermand

+0

Перемещение его в Array.prototype сделает его доступным для любого типа массива. – Rajesh

ответ

1

В типизации должны распространяться Array<T> интерфейс:

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

Добавление этого кода в файл .d.ts в папке/typings сделало трюк! – mvermand

+0

Примечание. Пожалуйста, предложите использовать менее общее название. Это может иметь проблемы и может переопределить исходную функцию 'Array.remove'. – Rajesh

+0

@Rajesh, 'Array' не имеет функции' remove'. И в любом случае вопрос заключается в том, как добавить типизацию. –

1

Расширение класса Array, с интерфейсом это просто, вы можете попробовать что-то вроде этого:

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(); 
+0

Есть ли способ сделать расширение массива только для массивов, содержащих определенные классы? то есть. Мои занятия[] ? – Gillardo

+0

@ Gillardo уверен с ограничением, взгляните на https://www.typescriptlang.org/docs/handbook/generics.html * Использование параметров типа в общих ограничениях * – InferOn