In this answer, we learn how to define tuples of length N
in typescript so that
TupleOf<string, 3>
is basically the same as the type [string, string, string]
.
Now I would like to use this in a class with a generic parameter N
like
class Dimension<N extends number> {
private data: TupleOf<number, N> = /* ?? what here ?? */;
}
yet I fail to come up with a type safe way to initialize the data property. It should be a length N
array of numbers, but I think this requires to convert the (trivial union) type N
to a value, which according to this answer this is not possible.
I could require any use site to provide an initial value to the constructor.
class Dimension<N extends number> {
private data: TupleOf<number, N>;
constructor(data: TupleOf<number, N>) {
this.data = data;
}
}
Yet in general there may be cases where this is cumbersome, so the question remains: is there a way to initialize the data without getting values into the constructor?