-
-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy patharray-last.ts
More file actions
35 lines (28 loc) · 937 Bytes
/
array-last.ts
File metadata and controls
35 lines (28 loc) · 937 Bytes
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
import type {LastArrayElement} from 'type-fest';
/**
Return the last item of an array with stronger typing for tuples.
This provides better type safety than `array[array.length - 1]` or `array.at(-1)`.
@example
```
import {arrayLast} from 'ts-extras';
const tuple = ['abc', 123, true] as const;
const last = arrayLast(tuple);
//=> true
// ^? true
const array = ['a', 'b', 'c'];
const maybeLast = arrayLast(array);
//=> 'c'
// ^? string | undefined
// Empty arrays
const empty: string[] = [];
const noLast = arrayLast(empty);
//=> undefined
// ^? string | undefined
```
@category Improved builtin
*/
export function arrayLast<const ArrayType extends readonly [...unknown[], unknown]>(array: ArrayType): LastArrayElement<ArrayType>;
export function arrayLast<ArrayType extends readonly unknown[]>(array: ArrayType): ArrayType[number] | undefined;
export function arrayLast(array: readonly unknown[]) {
return array.at(-1);
}