您可以将Match patterns 用于您的字段'type,这让您几乎可以做任何事情:
const notNullPattern = Match.Where(val => val !== null)
value : {
type : notNullPattern
}
(见Arrow functions)
请注意,这将允许除null 之外的所有内容,包括undefined。
以这种方式定义模式允许您在应用程序中的任何地方使用它们,包括in check:
check({
key : 'the key',
modified : Date.now(),
value : {} // or [], 42, false, 'hello ground', ...
}, optionsSchema)
Match.test(undefined, notNullPattern) //true
Match.test({}, notNullPattern) //true
Match.test(null, notNullPattern) //false
排除 one 值的更一般的解决方案是:
const notValuePattern =
unwantedValue => Match.Where(val => val !== unwantedValue))
其中的用法与上面类似:
Match.test(42, notValuePattern(null)) // true
请注意,由于使用了identity operator ===,它将特别是fail for NaN:
Match.test(NaN, notValuePattern(NaN)) // true :(
解决方案可能是:
const notValuePattern =
unwantedValue => Match.Where(val => Number.isNaN(unwantedValue)?
!Number.isNaN(val)
: val !== unwantedValue
)
如果您想要一个解决方案来排除架构中的某些特定值(与 Match.OneOf 相反),您可以使用以下内容:
const notOneOfPattern = (...unwantedValues) =>
Match.Where(val => !unwantedValues.includes(val)
)
这使用Array.prototype.includes 和... spread operator。使用如下:
Match.test(42, notOneOfPattern('self-conscious whale', 43)) // true
Match.test('tuna', notOneOfPattern('tyranny', 'tuna')) // false
Match.test('evil', notOneOfPattern('Plop', 'kittens')) // true
const disallowedValues = ['coffee', 'unicorns', 'bug-free software']
Match.test('bad thing', notOneOfPattern(...disallowedValues)) // true