幻影类型与多维数组:用类型标记数组的维度与单位
利用幻影类型参数标记数组维度,如 Matrix<3,4,'meters'>,在编译期检查矩阵乘法维度匹配与单位转换。 · 难度:入门 · +10XP
幻影类型与多维数组:用类型标记数组的维度与单位
幻影类型是不出现在运行时但用于类型标记的泛型参数。例如 type Matrix<R extends number, C extends number, U = 1> = number[] & { __rows: R; __cols: C; __unit: U }。通过类型运算实现矩阵乘法时强制约束 R1.Col === R2.Row,并且单位自动乘积。本教程将实现一个 2x2 矩阵乘法且验证单位匹配。
type Matrix<R, C, U> = number[] & { _rows: R; _cols: C; _unit: U };
type Multiply<A extends Matrix<Ra, Ca, Ua>, B extends Matrix<Rb, Cb, Ub>> =
Ca extends Rb ? Matrix<Ra, Cb, MultiplyUnits<Ua, Ub>> : never;
type Mat2x2 = Matrix<2, 2, 'm'>;
type Mat2x3 = Matrix<2, 3, 's'>;
type Result = Multiply<Mat2x2, Mat2x3>; // 错误 Ca(2) 与 Rb(2) 匹配但列数不匹配