Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make required property accept null, but not undefined with Vue.js

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 for undefined 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 is undefined (which happens when the prop is omitted)?

like image 519
Vince Varga Avatar asked Apr 04 '18 09:04

Vince Varga


1 Answers

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]"
like image 145
Emile Bergeron Avatar answered Sep 30 '22 04:09

Emile Bergeron