如何定义typescript类型多维矩阵嵌套数组 每层每个数组元素的长度仍然相同?
type FixedArray<T, D extends number> = T[] & {
length: D
}
type NestedArray<T> = T[] | NestedArray<T>[];
你快到了,你必须嵌套类型
FixedArray
。你可以做这样的事情 -
type FixedLengthArray<Length extends number, Type = unknown> = Type[] & { length: Length };
type MultDimArray<NumRows extends number, NumCols extends number, Type = unknown> = FixedLengthArray<NumRows, FixedLengthArray<NumCols, Type>>
let a: MultDimArray<2, 3, string> = [['a', 'd', 'c'], ['a', 'd', 'c']]