1 | import type {Subtract} from './subtract';
|
2 | import type {IsEqual} from './is-equal';
|
3 |
|
4 | type Recursive<T> = Array<Recursive<T>>;
|
5 |
|
6 | /**
|
7 | Creates a type that represents a multidimensional array of the given type and dimension.
|
8 |
|
9 | Use-cases:
|
10 | - Return a n-dimensional array from functions.
|
11 | - Declare a n-dimensional array by defining its dimensions rather than declaring `[]` repetitively.
|
12 | - Infer the dimensions of a n-dimensional array automatically from function arguments.
|
13 | - Avoid the need to know in advance the dimensions of a n-dimensional array allowing them to be dynamic.
|
14 |
|
15 | @example
|
16 | ```
|
17 | import type {MultidimensionalArray} from 'type-fest';
|
18 |
|
19 | function emptyMatrix<T extends number>(dimensions: T): MultidimensionalArray<unknown, T> {
|
20 | const matrix: unknown[] = [];
|
21 |
|
22 | let subMatrix = matrix;
|
23 | for (let dimension = 1; dimension < dimensions; ++dimension) {
|
24 | console.log(`Initializing dimension #${dimension}`);
|
25 |
|
26 | subMatrix[0] = [];
|
27 | subMatrix = subMatrix[0] as unknown[];
|
28 | }
|
29 |
|
30 | return matrix as MultidimensionalArray<unknown, T>;
|
31 | }
|
32 |
|
33 | const matrix = emptyMatrix(3);
|
34 |
|
35 | matrix[0][0][0] = 42;
|
36 | ```
|
37 |
|
38 | @category Array
|
39 | */
|
40 | export type MultidimensionalArray<Element, Dimensions extends number> = number extends Dimensions
|
41 | ? Recursive<Element>
|
42 | : IsEqual<Dimensions, 0> extends true
|
43 | ? Element
|
44 | : Array<MultidimensionalArray<Element, Subtract<Dimensions, 1>>>;
|