buhmann
buhmann

Reputation: 53

Add method to typed arrays in TypeScript

How can I add a method to a typed array like Array<MyClass>?

Consider a case where you have a typed array where it might make sense to offer a property/method to calculate a value by accessing all items of the array.

class Foo {
    date: Date
}

class FooArray extends Array<Foo> {

    dateInterval() {
        // Some algorithm that iterates over all dates to find
        // min/max
        return this.reduce(..)
    }
}

But something tells me that I'm going the wrong way. For example, FooArray.splice() returns the type Foo[], not FooArray, which makes total sense to me.

Can anyone point me into the right direction?

Upvotes: 2

Views: 87

Answers (1)

Sean Newell
Sean Newell

Reputation: 1113

I'll provide 2 options for you

Casting

Just explicitly add the splice method to override the inherited method to return your preferred type, with casts

splice() {
  let arr = super.splice();
  return new FooArray(arr); // or some other way of casting
}

Alternatively, wrapping

Wrapping

class FooArray {

    constructor(private arr: Foo[]) { /* maybe copy the array...? */ }    

    splice(start: number, end?: number) {
        return new FooArray(this.arr.splice(start, end));
    }
}

This way you must be explicit about what you expose, rather than mixing the inherited base class' methods that will return normal arrays. Take your pick.

Upvotes: 2

Related Questions