如何向类型化数组添加方法,如 Array<MyClass>
?
考虑这样一种情况,您有一个类型化数组,提供一个属性/方法来通过访问数组的所有项来计算值可能是有意义的。
class Foo {
date: Date
}
class FooArray extends Array<Foo> {
dateInterval() {
// Some algorithm that iterates over all dates to find
// min/max
return this.reduce(..)
}
}
但有件事告诉我,我走错了路。例如,FooArray.splice()
返回类型 Foo[]
,不是FooArray
,这对我来说完全有意义。
有人能指出我正确的方向吗?
最佳答案
我将为您提供 2 个选项
选角
只需显式添加 splice 方法来覆盖继承的方法即可返回您首选的类型,并进行强制转换
splice() {
let arr = super.splice();
return new FooArray(arr); // or some other way of casting
}
或者,包装
换行
class FooArray {
constructor(private arr: Foo[]) { /* maybe copy the array...? */ }
splice(start: number, end?: number) {
return new FooArray(this.arr.splice(start, end));
}
}
这样,您必须明确您公开的内容,而不是混合继承的基类的将返回普通数组的方法。任君选择。
关于arrays - 在 TypeScript 中向类型化数组添加方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44501328/