在TypeScript中扩展数组
如何为基本类型(例如数组)添加方法? 在全局模块中,这将被认可
interface Array {
remove(o): Array;
}
但是实际执行情况放在哪里?
5个解决方案
72 votes
您可以使用原型扩展Array:
interface Array {
remove(o: T): Array;
}
Array.prototype.remove = function (o) {
// code to remove "o"
return this;
}
如果您在模块内,则需要明确说明您是指全局299529881974472806806,而不是在模块内创建本地Array:
declare global {
interface Array {
remove(o: T): Array;
}
}
Fenton answered 2020-08-03T16:17:11Z
41 votes
从TypeScript 2.1开始,似乎是declare global。 请注意,Array.prototype的类型为2995299245047153153666,因此,如果要检查函数实现的一致性,最好自己添加一个泛型类型参数。
declare global {
interface Array {
re