Refinements
Superstruct allows you to constrain existing structs with further validation. This doesn't change the type of the struct, but simply introduces extra validation logic. This can be useful for example when ensuring that a string matches a specific RegExp.

empty

1
empty(string())
2
empty(array())
Copied!
1
''
2
[]
Copied!
empty enforces that a string, array, map, or set is empty.
🤖 Technically this is the same as using size of zero, but "empty" feels slightly nicer and will give a slightly easier to read error.

max

1
max(number(), 0)
Copied!
1
-1
Copied!
max enforces that a number struct is less than a threshold.
🤖 If you need an exclusive maxmimum you can pass { exclusive: true } as the third argument, like max(number(), 0, { exclusive: true }) for negative numbers.

min

1
min(number(), 9000)
Copied!
1
9001
Copied!
min enforces that a number struct is greater than a threshold.
🤖 If you need an exclusive minimum you can pass { exclusive: true } as the third argument, like min(number(), 0, { exclusive: true }) for positive numbers.

nonempty

1
nonempty(string())
2
nonempty(array())
Copied!
nonempty enforces that a string, array, map, or set is not empty. This does the opposite of empty.

pattern

1
pattern(string(), /\d+/)
Copied!
1
'123'
Copied!
pattern enforces that a string struct also matches a supplied RegExp.

size

1
size(string(), 1, 100)
2
size(array(number()), 0)
3
size(number(), 93, Infinity)
Copied!
1
'a string of text'
2
[]
3
Infinity
Copied!
size enforces that a number, string, array, map, or set struct also is within a certain min and max size (or length).
🤖 The max argument is optional and defaults to whatever you pass for min, which makes specifying exact sizes easy (just omit the max).

Custom Refinements

You can also define your own custom refinments that are specific to your application's requirements, like so:
1
import { number, refine } from 'superstruct'
2
3
const Positive = refine(number(), 'positive', (value) => value >= 0)
Copied!
This allows you to define more fine-grained runtime validation, while still preserving the number type at compile time.
Last modified 1mo ago