This document will show you:
- How to define a shape.
- How the descriptor properties of a type work with shapes.
There are 3 kinds of shapes, object, array and their combination.
Let us look into an example of the shape definition step by step.
import {shape} from 'skema'
const User = shape({
// 1
id: Number,
// 2
profile: shape({
// 3
birth: 'date',
// 4
name: 'string?'
})
})
-
The user id is a number, and
Number
is an alias of the built-in number type. -
To define a deep shape, just make the object deeper.
-
'date'
is also an alias -
'string?'
is equivalent to:
type({
type: 'string',
optional: true
})
For more information about optional type, see optional section below.
const user = User.from({
id: '123',
profile: {
birth: '1999-01-01',
name: 'Jack'
}
})
Then
user.id
is the number123
user.profile.birth
is anDate
object which time is1999-01-01
user.profile.name
is'Jack'
And how about the given data without id.
User.from({
profile: {
birth: '1999-01-01',
name: 'Jack'
}
})
// throw Error
// - code: NOT_OPTIONAL
// - message: key 'id' is not optional
// - path: ['id']
// - key: 'id'
It throws an error, what happens?
The built-in type Number
is not optional. If a property of a shape is not optional, and the given value does not contain the property, it will fail.
To fix this, you should either make the data right or change the shape:
shape({
// use string syntactic suger
id: 'number?'
})
shape({
// inherit a skema
id: type({
type: Number,
optional: true
})
})
More information about Type Inheritance, see this example.