Skema: Default Value
Default value of a property
by kaelzhang
HTML
<script src="https://unpkg.com/skema/umd/jsfiddle.js"></script>
<script src="https://unpkg.com/skema/umd/skema.min.js"></script>
JavaScript
const {
shape
} = Skema
log('example 1')
const LoginMethod = shape({
kind: {
default: 'FACEBOOK'
},
username: String
})
const lm = LoginMethod.from({
username: 'Steve'
})
success('kind:', lm.kind)
log('example 2')
const LoginMethod2 = shape({
kind: {
// If `default` is a function,
// it is treated as the getter of the default value
default: () => 'FACEBOOK'
},
username: String
})
const lm2 = LoginMethod2.from({
username: 'Steve'
})
success('kind:', lm2.kind)
log('example 3')
const LoginMethod3 = shape({
kind: {
// If we want the default value to be a function,
// use a function that returns the function
default: () => () => 'FACEBOOK'
},
username: String
})
const lm3 = LoginMethod3.from({
username: 'Steve'
})
success('function kind:', lm3.kind())
log('example 4')
const LoginMethod4 = shape({
kind: {
// We could access the parent object here to get different
// default values depends on the input object
default: function () {
return this.rawParent.username === 'Steve'
? 'APPLEID'
: 'FACEBOOK'
}
},
username: String
})
const lm4 = LoginMethod4.from({
username: 'Steve'
})
success('kind:', lm4.kind)
success('kind:', LoginMethod4.from({
username: 'Zark'
}).kind)