Coercing Data
Sometimes while validating input data you'll actually want to "coerce" it to change it in someway to help validation pass. The most common example of this is adding default values to properties, but it can also be used to parse multiple input formats, or cleanup inconsistent data.
To allow for these use cases, Superstruct has a concept called "coercion", which allows you to encode specific logic about how to transform a piece of data before validating it.

Default Values

Since defaults are such a common case, Superstruct comes with a defaulted helper that makes defining default values easy:
1
import { defaulted, create } from 'superstruct'
2
3
let i = 0
4
5
const User = object({
6
id: defaulted(number(), () => i++),
7
email: string(),
8
name: string(),
9
})
10
11
const data = {
12
name: 'Jane',
13
14
}
15
16
const user = create(data, User)
Copied!
Here the user object didn't default an id property. That's because any undefined values will be replaced with their default values instead.
Notice that we used create and not assert! This is an important distinction because we want to receive the return value of the newly coerced data.
The defaults helper also works with objects:
1
const User = defaulted(
2
object({
3
id: number(),
4
name: string(),
5
email: string(),
6
}),
7
{
8
id: () => i++,
9
}
10
)
Copied!

Custom Coercions

We've already covered default values, but sometimes you'll need to create coercions that aren't just defaulted undefined values, but instead transforming the input data from one format to another.
For example, maybe you want to ensure that a number is parsed from a string before passing it into the validator. To do that you can define a custom coercion:
1
import { coerce, number, string, create } from 'superstruct'
2
3
const MyNumber = coerce(number(), string(), (value) => parseFloat(value))
Copied!
Now instead of using assert() or is() you can use create() to apply your custom coercion logic:
1
import { create } from 'superstruct'
2
3
const data = '3.14'
4
const output = create(data, MyNumber)
5
// 3.14
Copied!
If the input data had been invalid or unable to be coerced an error would have been thrown instead.
Last modified 1mo ago