TypeScript utilities for dealing with array length. Of course, type predicates inside.
Useful for codebase with noUncheckedIndexedAccess
turned on.
npm i -D ts-array-length
Returns true
if arr.length === len
.
// const arr: string[]
if (hasLength(arr, 1)) {
// arr: readonly [string]
const str: string = arr[0];
}
Returns true
if arr.length >= len
.
// const arr: string[]
if (hasMinLength(arr, 1)) {
// arr: readonly [string, ...string[]]
const str: string = arr[0];
}
Returns true
if arr.length >= 1
.
// const arr: string[]
if (isNonEmpty(arr)) {
// arr: readonly [string, ...string[]]
const str: string = arr[0];
}
Tuple type whose element type is T
and has exact length N
.
// readonly [string, string, string]
type SSS = ReadonlyArrayExactLength<string, 3>;
Tuple type whose element type is T
and has at least N
elements.
// readonly [string, string, string, ...string[]]
type SSS = ReadonlyArrayMinLength<string, 3>;
MIT