-
-
Notifications
You must be signed in to change notification settings - Fork 11
/
array.at.ts
43 lines (42 loc) · 895 Bytes
/
array.at.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
import type { IsNumber } from '../number/is_number.js'
import type { IsTuple } from '../tuple/is_tuple.js'
import type { IndexAt } from './array_plus.index_at.js'
/**
* 🦴 *utilities*
*
* Gets the type of the array or tuple at positive or negative index `N`.
*
* Like `Array.at()`, this type supports negative numbers.
*
* @alias ArrayPlus.At
* @see https://github.com/microsoft/TypeScript/issues/53345#issuecomment-1477138167
*
* ```ts
* type R = At<[1, 2, 3], 2> // 3
* type R = At<[1, 2, 3], -1> // 3
* ```
*/
export type At<A extends readonly unknown[], N extends number, Fail = never> = IndexAt<
A,
N,
Fail,
Fail,
Fail
> extends infer I
? I extends number
? IsTuple.$<
A,
{
$then: IsNumber.$<
I,
{
exact: true
$then: A[I] | undefined
$else: A[I]
}
>
$else: A[I] | undefined
}
>
: Fail
: never