sample
Selects an arbitrary element from the array.
function sample<T>(arr: T[]): T | undefined;
function sample<T>(arr: NonEmptyArray<T>): T;
- If the array is empty, it returns
undefined. - If the array can be empty (
T[]), it returnsT | undefined. - If the array cannot be empty (
NonEmptyArray<T>), it returnsT.- Use
isNonEmptyArraytype guard to ensure that the array is not empty.
- Use
Examples
// undefined
sample([]);
// May return 1 or 2
sample([1, 2]);
// May return '1', '2', or '3'
sample(['1', '2', '3']);