2016-11-17 106 views
0

我已经为JavaScript Array创建了一个polyfill;如何通知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埋怨卸下摆臂方法的用法:

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); 
} 

感谢

+0

为什么不使它成为'DocType'本身的一部分。 – Rajesh

+0

remove方法需要成为DocType的“数组”的一部分。不在DocType本身! – mvermand

+0

将它移动到Array.prototype将使它可用于任何类型的数组。 – Rajesh

回答

1

的分型应扩大Array<T>接口:

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

将此代码添加到我的/ typings文件夹中的.d.ts文件中,实现了诀窍! – 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