Coercions
Superstruct allows structs to be augmented with coercion logic, letting you to transform input data before validating it. This is most commonly used to apply default values to an input, but it can be used for more complex cases like pre-trimming strings, or pre-parsing inputs.
defaulted
defaulted
defaulted
augments a struct to add coercion logic for default values, which are applied when the input is undefined
.
🤖 If you add
defaulted
to anobject
struct with a dictionary of values, those values will be mixed in one-by-one, so the input doesn't need to beundefined
, but certain properties can beundefined
.
trimmed
trimmed
trimmed
arguments a struct to ensure that any string input values are trimmed.
Custom Coercions
You can also define your own custom coercions that are specific to your application's requirements, like so:
The second argument to coerce
is a struct narrowing the types of input values you want to try coercion. In the example above, the coercion function will only ever be called when the input is a string—booleans would ignore coercion and fail normally.
🤖 If you want to run coercion for any type of input, use the
unknown()
struct to run it in all cases.
Last updated