6

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

1 Answer 1

8

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]"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.