DEV Community

mikkergimenez
mikkergimenez

Posted on

Extending generic collection classes in Typescript

I'm researching some Typescript that won't compile, so I'm going to layout the problem here and I'll post the answer alter if/when I find it. (Answer Below!)

I have a base Generic which can accept strings, numbers, booleans, strings[] and numbers[]

export default class ParameterValue<
  T extends string | number | boolean | string[] | number[]
> {
  _val: T

  private setValue(newValue: T) {
    this._val = newValue
  }
}
Enter fullscreen mode Exit fullscreen mode

I want to extend this to work with arrays specifically.

export default class ArrayParameterValue<
  T extends string | number
> extends ParameterValue<T[]> {

  private addValue(newValue: T) {
    if (!this._val.contains(newValue)) {
      this._val.push(newValue);
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

But I'm getting the following Typescript Error:

Type 'T[]' does not satisfy the constraint 'string | number | boolean | string[] | number[]'.
  Type 'T[]' is not assignable to type 'string[]'.
    Type 'T' is not assignable to type 'string'.
      Type 'string | number' is not assignable to type 'string'.
        Type 'number' is not assignable to type 'string'.ts(2344)
Enter fullscreen mode Exit fullscreen mode

The Answer

I think the answer is that BaseParameter must accept type Array.

string[] and number[] can't either on their own accept

string | number

, so there's an error.

In fact I was able to make my code a bit tighter because I could remove string[] and number[] as types and replace them with

T extends string | number | boolean | Array<string | number>

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay