Arrays
Array and tuple decoders for validating collections of values.
array
function array( decoder: Decoder<T> ): Decoder<T[]> (source)
Accepts arrays of whatever the given decoder accepts.
Try it
| Input | Result |
|---|---|
| ["hello", "world"] | |
| [] | |
| [ "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.
Equivalent to sized(array(decoder), { min: 1 }).
Try it
| 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.
Try it
| 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.
Try it
| 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
function sized( decoder: Decoder<T[]>, options: SizeOptions ): Decoder<T[]> (source)
Available since 2.9.
Takes any array decoder and rejects values that don't match the given size constraints. Also works with strings and sets.
SizeOptions accepts min, max, or size (shorthand for exact length).
Try it
| 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 |