import { is, define, object, string } from 'superstruct'
import isUuid from 'is-uuid'
import isEmail from 'is-email'
const Email = define('Email', isEmail)
const Uuid = define('Uuid', isUuid.v4)
const User = object({
id: Uuid,
email: Email,
name: string(),
})
const data = {
id: 'c8d63140-a1f7-45e0-bfc6-df72973fea86',
email: '[email protected]',
name: 'Jane',
}
if (is(data, User)) {
// Your data is guaranteed to be valid in this block.
}import { create, object, number, string, defaulted } from 'superstruct'
const User = object({
id: defaulted(number(), () => 1),
name: string(),
})
const data = {
name: 'Jane',
}
// You can apply the defaults to your data while validating.
const user = create(data, User)
// {
// id: 1,
// name: 'Jane',
// }import { is, object, number, string } from 'superstruct'
const User = object({
id: number(),
name: string()
})
const data: unknown = { ... }
if (is(data, User)) {
// TypeScript knows the shape of `data` here, so it is safe to access
// properties like `data.id` and `data.name`.
}