Skip to main content

minArrayLength

The minArrayLength modifier is used to contraint length ofarray values. It also changes the return validation type – tuples with given number of elements are returned instead of arrays:

const len10Validator = λ(array(number()), minArrayLength(2), validate)([]);
const result = validate(len10Validator)([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]);
// type of result is
// readonly [number, number, ...number[]]

As a result, it makes using such arrays/tuples more typesafe. Notice how the type of the thirdElement is different:

// number
const firstElement = result[0];
// number
const tenthElement = result[1];
// number | undefined
const thirdElement = result[2];

Type instantiation is excessively deep and possibly infinite

On rare occasions you may come across the following TypeScript error: Type instantiation is excessively deep and possibly infinite.ts(2589). It's a limitation of the TypeScript compiler when used on very deeply nested conditional types such as the tuples generated by the minArrayLength modifier.

Should this issue ever occur to you, please override the inferred generic parameter with number:

// error in compile-time
const whoopsieDaisyValidator = λ(array(number()), minArrayLength(100000), validate)([]);

// fallback to less-typesafe array: readonly number[]
const better = λ(array(number()), minArrayLength<number>(100000), validate)([]);