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