Vince Varga
Vince Varga

Reputation: 6918

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)?

Upvotes: 6

Views: 12662

Answers (1)

Emile Bergeron
Emile Bergeron

Reputation: 17430

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]"

Upvotes: 8

Related Questions