1

I want to implement a method to filter some types of array in a certain way. So far I could achive this with this code:

  const isActiveBarSettingsBarF = (
        settingsBar: ISettingsBar[],
        bar: number
    ) => settingsBar[bar - 1].active !== false;

declare global {
    interface Array<T> {
        isActiveBarSettingsBar(settingsBar: ISettingsBar[]): ISettingsBar[];
    }
}

Array.prototype.isActiveBarSettingsBar = function isActiveBarSettingsBar(
    settingsBar: ISettingsBar[]
) {
    return this.filter((b: ISettingsBar) =>
        isActiveBarSettingsBarF(settingsBar, b.bar)
    );

The problem is this method is accessible for any type of array and I would like only to be for arrays of type ISettingsBar[].

If instead I do something like:

declare global {
    interface Array<ISettingsBar> {
        isActiveBarSettingsBar(settingsBar: ISettingsBar[]): ISettingsBar[];
    }
}

I get an error saying, all declarations of array must have identical type parameters.

Any idea? Thank you very much

pepinillo6969
  • 423
  • 6
  • 15
  • 1
    Extending a built in prototype with a method that only exists when instances of that prototype contain objects of a certain type is a bad plan. I think a simple function that you can import where you want and doesn't modify any global scopes will serve you far better. [Like this](https://tsplay.dev/mAKJkw) – Alex Wayne Jun 21 '22 at 16:41
  • What is `ISettingsBar`? Please provide a self-contained [mre] that clearly demonstrates the issue you are facing, as plain text in the body of your post. Ideally I could paste such code into a standalone IDE and immediately get to work solving the problem without first needing to re-create it. So there should be no pseudocode, typos, unrelated errors, or undeclared types or values. (If you want to provide a [playground link](https://tsplay.dev/mAK8vw) that's great, but please also put the full example in the body of the post as text.) – jcalz Jun 21 '22 at 18:39

0 Answers0