As a newcomer to Typescript and generics, I am unsure if I have encountered a bug/limitation of Typescript or if I am missing the correct approach to achieve my desired outcome.
I have a base class called Widget
which is generic and holds a value of type T
. This value can be of any type such as string
, number
, etc.
My goal is to create a subclass of Widget
that will store an Array<T>
as its value. For example, it could hold arrays like string[]
, Date[]
, and so on.
Here is an example of how it would be used:
let w = new Widget<string>();
w.value = "abc";
let aw = new ArrayWidget<number[]>();
aw.value = [1, 2, 3];
The closest solution I have found so far is this:
class Widget<T> {
public value:T;
}
class ArrayWidget<U extends T[], T> extends Widget<U> {
setValue() {
let v = new Array<T>();
this.value = v; // error: Type 'T[]' is not assignable to type 'U'
}
}
let aw = new ArrayWidget<string[], string>();
aw.value = ["a", "b", "c"];
How can I specify that the generic class ArrayWidget
should actually be an array of <T>
? Currently, I need to explicitly cast like this:
this.value = v as U;
Once I do this, everything works as expected in the consuming code. Thank you!