2

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks, I was hoping for some magic, but being explicit about what is exposed is probably just the way to go.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.