diff --git a/source/array-at.d.ts b/source/array-at.d.ts index 9c94e5f5..0271ee19 100644 --- a/source/array-at.d.ts +++ b/source/array-at.d.ts @@ -7,6 +7,57 @@ import type {Subtract} from './subtract.d.ts'; import type {Sum} from './sum.d.ts'; import type {UnknownArray} from './unknown-array.d.ts'; +/** +Return the element at the given index of the given array. + +Use-case: Get the element at a specific index of an array. + +Like [`Array#at()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at) but for types. + +@example +``` +import type {ArrayAt} from 'type-fest'; + +// Positive index +type A = ArrayAt<['a', 'b', 'c', 'd'], 1>; +//=> 'b' + +// Negative index +type B = ArrayAt<['a', 'b', 'c', 'd'], -4>; +//=> 'a' + +// Positive index with optional elements +type C = ArrayAt<['a', 'b', 'c'?, 'd'?], 3>; +//=> 'd' | undefined + +// Negative index with optional elements +type D = ArrayAt<['a', 'b', 'c'?, 'd'?], -2>; +//=> 'a' | 'b' | 'c' + +// Positive index with rest element and optional elements +type E = ArrayAt<['a', 'b', 'c'?, ...number[]], 3>; +//=> number | undefined + +// Negative index with rest element and optional elements +type F = ArrayAt<['a', 'b', 'c'?, ...number[]], -1>; +//=> 'b' | 'c' | number + +// Positive index with rest element in middle +type G = ArrayAt<['a', 'b', 'c', ...number[], 'd', 'e'], 4>; +//=> number | 'd' | 'e' + +// Negative index with rest element in middle +type H = ArrayAt<['a', 'b', ...number[], 'c', 'd', 'e'], -5>; +//=> 'a' | 'b' | number + +// Out-of-bounds positive index +type I = ArrayAt<['a', 'b'], 5>; +//=> undefined + +// Out-of-bounds negative index +type J = ArrayAt<['a', 'b'], -3>; +//=> undefined +*/ export type ArrayAt = TArray extends unknown // For distributing `Array_` ? Index extends unknown // For distributing `Index`