I am looking to create a versatile class for squared matrices that can accommodate matrices of any size. My aim is to develop standard methods such as addition and multiplication specifically designed for matrices of equal dimensions.
The objective is to consolidate all matrix types within one class while being able to identify size errors at compile time rather than during execution.
In my attempt, I experimented with using a generic type defined by the union of sizes I want to include, like Class Matrix<S = 3|4>
. However, I struggled to figure out how to test if S == 3
or S == 4
, and handle it accordingly.
Although I recognize that I could implement an abstract matrix class and extend it for each required size, I find this approach quite laborious...
UPDATE
The solution provided to me seems to be effective. Additionally, I would like to share a helpful tip. To define a multiplication operation with compile-time error checking, you can introduce generic types in the parameters, as demonstrated below:
type Size = 1|2|3|4;
class Matrix<I extends Size, J extends Size> {
readonly iMax: I;
readonly jMax: J;
// add coefficients
constructor(iMax: I, jMax: J){
this.iMax = iMax;
this.jMax = jMax;
// add coefficients
}
mult<K extends Size>(x: Matrix<J,K>): Matrix<I,K>{
// Compute the product
}
}
new Matrix(3,3).mult(new Matrix(2,2); // Error catch on compilation.