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>

Top comments (0)