You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

39 lines
1.4KB

  1. /**
  2. Methods to exclude.
  3. */
  4. type ArrayLengthMutationKeys = 'splice' | 'push' | 'pop' | 'shift' | 'unshift';
  5. /**
  6. 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.
  7. Please participate in [this issue](https://github.com/microsoft/TypeScript/issues/26223) if you want to have a similiar type built into TypeScript.
  8. Use-cases:
  9. - Declaring fixed-length tuples or arrays with a large number of items.
  10. - 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.
  11. - Creating an array of coordinates with a static length, for example, length of 3 for a 3D vector.
  12. @example
  13. ```
  14. import {FixedLengthArray} from 'type-fest';
  15. type FencingTeam = FixedLengthArray<string, 3>;
  16. const guestFencingTeam: FencingTeam = ['Josh', 'Michael', 'Robert'];
  17. const homeFencingTeam: FencingTeam = ['George', 'John'];
  18. //=> error TS2322: Type string[] is not assignable to type 'FencingTeam'
  19. guestFencingTeam.push('Sam');
  20. //=> error TS2339: Property 'push' does not exist on type 'FencingTeam'
  21. ```
  22. */
  23. export type FixedLengthArray<Element, Length extends number, ArrayPrototype = [Element, ...Element[]]> = Pick<
  24. ArrayPrototype,
  25. Exclude<keyof ArrayPrototype, ArrayLengthMutationKeys>
  26. > & {
  27. [index: number]: Element;
  28. [Symbol.iterator]: () => IterableIterator<Element>;
  29. readonly length: Length;
  30. };