-
Notifications
You must be signed in to change notification settings - Fork 220
/
default-values.js
38 lines (34 loc) · 753 Bytes
/
default-values.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import {
boolean,
create,
date,
defaulted,
number,
object,
string,
} from 'superstruct'
// Define an auto-incrementing unique id.
let uid = 1
// Define a struct, with properties with default values.
const User = object({
id: defaulted(number(), () => uid++),
name: string(),
email: string(),
is_admin: defaulted(boolean(), false),
created_at: defaulted(date(), () => new Date()),
})
// Define data to be validated.
const data = {
name: 'Jane Smith',
email: '[email protected]',
}
// Coerce the data during validation, using the struct's default values.
const user = create(data, User)
// {
// id: 1,
// name: 'Jane Smith',
// email: '[email protected]',
// age: 42,
// is_admin: false,
// created_at: Date,
// }