Arrays
Array and tuple decoders for validating collections of values.
array
function array( decoder: Decoder<T>, options?: SizeOptions ): Decoder<T[]> (source)
Accepts arrays of whatever the given decoder accepts.
| Input | Result |
|---|---|
| ["hello", "world"] | |
| [] | |
| [ "hello", 1.2, ^^^ Must be string (at index 1) ] |
The optional options argument constrains the array's length. It accepts min, max, or
size (shorthand for an exact length), and is checked before any item is decoded. See
limiting array sizes.
The options argument to array() is available since 2.11.
| Input | Result |
|---|---|
| ["hello", "world"] | |
| [] ^^ Must have at least 1 item | |
| [ "a", "b", "c", "d", ] ^ Must have at most 3 items | |
| [ "hello", 1.2, ^^^ Must be string (at index 1) ] |
nonEmptyArray
function nonEmptyArray( decoder: Decoder<T> ): Decoder<[T, ...T[]]> (source)
Like array(), but will reject arrays with 0 elements.
Accepts the same inputs as array(decoder, { min: 1 }), but its return type is
[T, ...T[]] instead of T[], so TypeScript knows the first element exists. Use it when
that type is useful to you, and array(decoder, { min: 1 }) otherwise.
| Input | Result |
|---|---|
| ["hello", "world"] | |
| [ "hello", 1.2, ^^^ Must be string (at index 1) ] | |
| [] ^^ Must have at least 1 item |
poja
poja: Decoder<unknown[]> (source)
Accepts any array, but doesn't validate its items further.
"poja" means "plain old JavaScript array", a play on pojo.
| Input | Result |
|---|---|
| [1, "hi", true] | |
| ["hello", "world"] | |
| [] | |
| {} ^^ Must be an array | |
| "hi" ^^^^ Must be an array |
tuple
function tuple( Decoder<A>, Decoder<B>, ... ): Decoder<[A, B, ...]> (source)
Accepts a tuple (an array with exactly n items) of values accepted by the n given decoders.
| Input | Result |
|---|---|
| ["hello", 1.2] | |
| [] ^^ Must be a 2-tuple | |
| [ "hello", "world", ^^^^^^^ Must be number ] | |
| [ "a", 1, "c", ] ^ Must be a 2-tuple |
Limiting array sizes
Available since 2.11.
To constrain an array's length, pass SizeOptions to array() as its second
argument. It accepts min, max, or size (shorthand for exact length).
| Input | Result |
|---|---|
| [1, 2, 3] | |
| [1, 2] | |
| [ 1, ] ^ Must have at least 2 items | |
| [ 1, 2, 3, 4, 5, ] ^ Must have at most 4 items | |
| [] ^^ Must have at least 2 items |
The length is checked before any item is decoded, so an out-of-range input reports the length, not its first bad item, and large inputs are rejected without walking them.