Make required property accept null, but not undefined with Vue.js
From the documentation on props validation
Basic type check (
null
matches any type)
After checking the source, the basic types are defined with the following regex.
const simpleCheckRE = /^(String|Number|Boolean|Function|Symbol)$/
So type: Object,
is incorrect. You could remove the type
prop check, keeping the required
and custom validator
checks.
@Prop({
required: true,
validator: v => typeof v === 'object',
})
If you just want to ensure that the prop is at least set to null, you could just remove the required
check and add a simple default: null
.
@Prop({
type: Object,
default: null,
})
Your reference to Vue isObject
utils is not used in the type check. It uses isPlainObject
.
Which can distinguish null
by doing the equivalent of:
Object.prototype.toString.call(null)
// => "[object Null]"
Vince Varga
Updated on June 23, 2022Comments
-
Vince Varga almost 2 years
I'd like to accept objects and null (Vue.js checks for null values for objects, even though
typeof null === 'object'
) in one of my components, but I want to make the validation fail forundefined
values.What I have tried (using
vue-property-decorator
)@Prop({ required: true, type: Object, validator: v => typeof v === 'object' }) @Prop({ required: true, validator: v => typeof v === 'object' }) // I got an error: //> Expected Object, got Null. @Prop({ validator: v => typeof v === 'object' }) // Let's undefined through, so when I don't specify the prop, I get no warnings // making the validator useless for my purposes
How can I accept objects (including
null
) as a property while making sure that the developer using my component receives a warning if the value isundefined
(which happens when the prop is omitted)?