typescriptvue.jsvue-sfcvue-script-setup

What TypeScript type is used to pass a class in Vue 3 script setup prop definitions?


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?


Solution

  • The class binding value can be one of the following types:

    or a mixed array of the above:

    So the itemClass type should be the union of these types:

    defineProps<{
      itemClass?: string | Record<string, boolean> | (string | Record<string, boolean>)[]
    }>()
    

    demo