在 TypeScript 中扩展数组 [英] Extending Array in TypeScript
本文介绍了在 TypeScript 中扩展数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何将方法添加到基本类型,比如 Array?在全局模块中,这将被识别
How to add a method to a base type, say Array? In the global module this will be recognized
interface Array {
remove(o): Array;
}
但是将实际实现放在哪里?
but where to put the actual implementation?
推荐答案
可以使用原型扩展Array:
You can use the prototype to extend Array:
interface Array<T> {
remove(o: T): Array<T>;
}
Array.prototype.remove = function (o) {
// code to remove "o"
return this;
}
如果你在一个模块中,你需要明确你指的是全局Array
,而不是创建一个局部Array
> 模块内的界面:
If you are within a module, you will need to make it clear that you are referring to the global Array<T>
, not creating a local Array<T>
interface within your module:
declare global {
interface Array<T> {
remove(o: T): Array<T>;
}
}
这篇关于在 TypeScript 中扩展数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文