Closed
Description
What problem does this feature solve?
I haven't found a way to properly define required nullable props.
Why
I want to be able to define a component property that is required
and accepts null
as a value (along with "normal" types like String, Number, etc.)
I consider null
as a value, which indicates an absence of a value.
undefined
means the value is unknown (e.g. we don't know it yet because we haven't got a response from API request).
Hence, null
and undefined
should not be treated the same.
Problems with current workarounds
1. Marking the property as optional.
- If there is a bug in the code and a parent component does not specify the property at all, then I won't get any warnings from Vue.
- If there is a bug in the code and a parent component provides
undefined
as a value, then I won't get any warnings from Vue. - Typescript complains about the following code
props: {
category: {
type: String,
required: false,
}
},
setup(props) {
const { category } = toRefs(props);
console.log(category.value)
because TS considers category
as possibly 'undefined'
2. Mark the prop as required and hint TS about possible values
props: {
category: {
type: String as () => string | null,
required: true,
}
}
I get Vue warnings in the console "[Vue warn]: Invalid prop: type check failed for prop “category”. Expected String with value “null”, got Null"
What does the proposed API look like?
I have 2 ideas:
- Adding
null
to the list of possibletype
values https://v3.vuejs.org/guide/component-props.html#type-checks
So that I can define the prop the following way:
props: {
category: {
type: [String, null],
required: true,
}
}
- Adding
nullable
option to the prop object (https://v3.vuejs.org/api/options-data.html#props):
props: {
category: {
type: String,
required: true,
nullable: true,
}
}