UNPKG

1.63 kBTypeScriptView Raw
1/**
2Methods to exclude.
3*/
4type ArrayLengthMutationKeys = 'splice' | 'push' | 'pop' | 'shift' | 'unshift';
5
6/**
7Create 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
9Please participate in [this issue](https://github.com/microsoft/TypeScript/issues/26223) if you want to have a similar type built into TypeScript.
10
11Use-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
16Note: This type does not prevent out-of-bounds access. Prefer `ReadonlyTuple` unless you need mutability.
17
18@example
19```
20import type {FixedLengthArray} from 'type-fest';
21
22type FencingTeam = FixedLengthArray<string, 3>;
23
24const guestFencingTeam: FencingTeam = ['Josh', 'Michael', 'Robert'];
25
26const homeFencingTeam: FencingTeam = ['George', 'John'];
27//=> error TS2322: Type string[] is not assignable to type 'FencingTeam'
28
29guestFencingTeam.push('Sam');
30//=> error TS2339: Property 'push' does not exist on type 'FencingTeam'
31```
32
33@category Array
34@see ReadonlyTuple
35*/
36export type FixedLengthArray<Element, Length extends number, ArrayPrototype = [Element, ...Element[]]> = Pick<
37ArrayPrototype,
38Exclude<keyof ArrayPrototype, ArrayLengthMutationKeys>
39> & {
40 [index: number]: Element;
41 [Symbol.iterator]: () => IterableIterator<Element>;
42 readonly length: Length;
43};