Soviut
Soviut

Reputation: 91722

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?

Upvotes: 4

Views: 2732

Answers (2)

Tomas Randus
Tomas Randus

Reputation: 2305

With Vue 3.2.39 I use this:

  import { HTMLAttributes } from "vue";

  const props = defineProps<{
    class?: HTMLAttributes["class"];
  }>();

Anyway it is still any. Hope Vue will have proper types soon.

Upvotes: 5

tony19
tony19

Reputation: 138706

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>)[]
}>()

demo

Upvotes: 8

Related Questions