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

Time:01-15

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 :>...</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?

CodePudding user response:

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

string

<div :>

Record<string, boolean> (Object syntax)

<div :>

or a mixed array of the above

(string | Record<string, boolean>)[] (Array syntax)

<div :>

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

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

demo

  •  Tags:  
  • Related