-
-
Notifications
You must be signed in to change notification settings - Fork 547
/
last-array-element.d.ts
38 lines (30 loc) · 1.33 KB
/
last-array-element.d.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
/**
Extracts the type of the last element of an array.
Use-case: Defining the return type of functions that extract the last element of an array, for example [`lodash.last`](https://lodash.com/docs/4.17.15#last).
@example
```
import type {LastArrayElement} from 'type-fest';
declare function lastOf<V extends readonly any[]>(array: V): LastArrayElement<V>;
const array = ['foo', 2];
typeof lastOf(array);
//=> number
const array = ['foo', 2] as const;
typeof lastOf(array);
//=> 2
```
@category Array
@category Template literal
*/
export type LastArrayElement<Elements extends readonly unknown[], ElementBeforeTailingSpreadElement = never> =
// If the last element of an array is a spread element, the `LastArrayElement` result should be `'the type of the element before the spread element' | 'the type of the spread element'`.
Elements extends readonly []
? ElementBeforeTailingSpreadElement
: Elements extends readonly [...infer U, infer V]
? V
: Elements extends readonly [infer U, ...infer V]
// If we return `V[number] | U` directly, it would be wrong for `[[string, boolean, object, ...number[]]`.
// So we need to recurse type `V` and carry over the type of the element before the spread element.
? LastArrayElement<V, U>
: Elements extends ReadonlyArray<infer U>
? U | ElementBeforeTailingSpreadElement
: never;