UNPKG

1.51 kBTypeScriptView Raw
1import type {Subtract} from './subtract';
2import type {IsEqual} from './is-equal';
3
4type Recursive<T> = ReadonlyArray<Recursive<T>>;
5
6/**
7Creates a type that represents a multidimensional readonly array that of the given type and dimension.
8
9Use-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```
17import type {MultidimensionalReadonlyArray} from 'type-fest';
18
19function emptyMatrix<T extends number>(dimensions: T): MultidimensionalReadonlyArray<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 if (dimension < dimensions - 1) {
28 subMatrix = subMatrix[0] as unknown[];
29 } else {
30 subMatrix[0] = 42;
31 }
32 }
33
34 return matrix as MultidimensionalReadonlyArray<unknown, T>;
35}
36
37const matrix = emptyMatrix(3);
38
39const answer = matrix[0][0][0]; // 42
40```
41
42@category Array
43*/
44export type MultidimensionalReadonlyArray<Element, Dimensions extends number> = number extends Dimensions
45 ? Recursive<Element>
46 : IsEqual<Dimensions, 0> extends true
47 ? Element
48 : ReadonlyArray<MultidimensionalReadonlyArray<Element, Subtract<Dimensions, 1>>>;