1 | /**
|
2 | Methods to exclude.
|
3 | */
|
4 | type ArrayLengthMutationKeys = 'splice' | 'push' | 'pop' | 'shift' | 'unshift';
|
5 |
|
6 | /**
|
7 | Create a type that represents an array of the given type and length. The array's length and the `Array` prototype methods that manipulate its length are excluded in the resulting type.
|
8 |
|
9 | Please participate in [this issue](https://github.com/microsoft/TypeScript/issues/26223) if you want to have a similar type built into TypeScript.
|
10 |
|
11 | Use-cases:
|
12 | - Declaring fixed-length tuples or arrays with a large number of items.
|
13 | - Creating a range union (for example, `0 | 1 | 2 | 3 | 4` from the keys of such a type) without having to resort to recursive types.
|
14 | - Creating an array of coordinates with a static length, for example, length of 3 for a 3D vector.
|
15 |
|
16 | Note: This type does not prevent out-of-bounds access. Prefer `ReadonlyTuple` unless you need mutability.
|
17 |
|
18 | @example
|
19 | ```
|
20 | import type {FixedLengthArray} from 'type-fest';
|
21 |
|
22 | type FencingTeam = FixedLengthArray<string, 3>;
|
23 |
|
24 | const guestFencingTeam: FencingTeam = ['Josh', 'Michael', 'Robert'];
|
25 |
|
26 | const homeFencingTeam: FencingTeam = ['George', 'John'];
|
27 | //=> error TS2322: Type string[] is not assignable to type 'FencingTeam'
|
28 |
|
29 | guestFencingTeam.push('Sam');
|
30 | //=> error TS2339: Property 'push' does not exist on type 'FencingTeam'
|
31 | ```
|
32 |
|
33 | @category Array
|
34 | @see ReadonlyTuple
|
35 | */
|
36 | export type FixedLengthArray<Element, Length extends number, ArrayPrototype = [Element, ...Element[]]> = Pick<
|
37 | ArrayPrototype,
|
38 | Exclude<keyof ArrayPrototype, ArrayLengthMutationKeys>
|
39 | > & {
|
40 | [index: number]: Element;
|
41 | [Symbol.iterator]: () => IterableIterator<Element>;
|
42 | readonly length: Length;
|
43 | };
|