gpt4 book ai didi

javascript - 如何通知 TypeScript 编译器对 JS 数组原型(prototype)的扩展?

转载 作者:行者123 更新时间:2023-12-02 13:56:42 25 4
gpt4 key购买 nike

我已经为 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):

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

关于javascript - 如何通知 TypeScript 编译器对 JS 数组原型(prototype)的扩展?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40650245/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com