I have a Vue 3 single file component using the script setup approach. One of the props I want to define will be accepting the equivalent of the class
attribute. This means the prop value could be a string, an expression, an array, or object. The problem comes when I try to use withDefaults()
to assign a default empty string value to this prop.
withDefaults(
defineProps<{
itemClass?: unknown
}>(),
{
itemClass: '',
}
)
Which is bound as
<div :class="itemClass">...</div>
I'm trying to avoid using any
as the type. I tried unknown
but get an error when I try to give it a default value. The temporary solution seems to be to simply remove the default value, but there may be cases where I want a default value set.
Is there a specific type for the Vue class
attribute?
The class
binding value can be one of the following types:
string
Example:
<div :class="myStringProp">
Record<string, boolean>
(Object syntax)
Example:
<div :class="{ active: true, error: true }">
or a mixed array of the above:
(string | Record<string, boolean>)[]
(Array syntax)
Example:
<div :class="['item', { active: true, error: true }]">
So the itemClass
type should be the union of these types:
defineProps<{
itemClass?: string | Record<string, boolean> | (string | Record<string, boolean>)[]
}>()